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 (2016, retired 2019) Dictionaries Word Count

how do i increment the count in my_dict

well this is how far i have gotten so far. the out put, to my knowledge, is all correct but my counter will not increase...

going about this problem any other way leaves me with the problem of creating a key without a value which i found to be impossible so my next best step is to introduce and try to increase the counter by the amount of time the key is found in the dictionary....

any help or advice on what i should do or even if there is something in my code now that i need to look at or???

please and thank you

wordcount.py
# E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.

def word_count(string):
    my_dict = {}
    string = string.lower()
    string = string.split()
    counter = 1
    for word in string:
        my_dict[word] = counter
        if my_dict[word] in my_dict:
            counter += 1
        else:
            counter = 1
    return my_dict   
Cameron Nilon
Cameron Nilon
15,601 Points

Hey Terry,

You are quite close. Your problem is that you applying counter of 1 across the entire dict, but if you simply remove that line you will get an error. So for a solution use update.

Here is an example.

def word_count(string):
   words = string.lower()
   word_list = words.split()
   word_count = {}
   for word in word_list:
      if word in word_count:
         word_count[word] += 1
      else:
         word_count.update({word:1})  # this is where update comes in

   return word_count