Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries Word Count

Alex Rendon
Alex Rendon
7,498 Points

How can I count the items repeated in a list? Help me please.

I don't understand it, who can help me?

2 Answers

Chase Marchione
Chase Marchione
155,055 Points

Hi Alex,

1) The challenge asks us to create a function named word_count, which takes a string as a parameter. I named my string 'examp_string' for this exercise.

2) Inside of the function, we want to create a variable for an empty dictionary. We'll provide data for this empty dictionary later.

3) Next up, we want to write a for loop that will cycle through each word in our string. We will use the split method on our example string so that our string is evaluated as if it is a list. Our for loop is iterating through this list for each word.

4) Then, we want to write an if statement within the for loop. This if block will increment (add) to the value of each key by 1 if the word has already appeared, or create a new key with an initialized value of 1 if it has not.

5) Finally, we will return the dictionary--which is now populated with each word of our string and how many times each word appears.

def word_count(examp_string):
  string_dict = {}
  for word in examp_string.split():
    if word in string_dict:
        string_dict[word] += 1
    else:
        string_dict[word] = 1
  return string_dict

Hope this helps!

Alex Rendon
Alex Rendon
7,498 Points

Hey CJ, thanks so much!, now I can understand it. :)

I see how the function works, you did a great job of explaining this

Could you provide an example of further function and code for running this function? What would we add to input words into this and print out the output of information imputed into this function? How could I make this run? maybe would I go back and sort of hybrid this into the shopping list exercise to experiment with this function running, adding words in and getting the result of this function?