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

Word_count challenge: I checked my code in the work space and it works fine, but I get an error here.

Not sure how to fix this

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):
    words = string.split()
    word_dict = {}
    for word in words:
        if word.lower() in word_dict:
            count += 1
            word_dict.update({word.lower(): count})
        else:
            count = 1
            word_dict.update({word.lower(): count})
    return(word_dict)   

1 Answer

Try the given phrase twice with your code:

word_count("I do not like it Sam I Am I do not like it Sam I Am")

count keeps incrementing with (wrong) result

{'i': 8, 'do': 3, 'not': 4, 'like': 5, 'it': 6, 'sam': 7, 'am': 9}  

Oh I just ran it and now I see the problem. Seems like there is an issue with the in statement so used in my for loop. I’ll have to play around with it to figure out how to change it

For some reason, it’s counting the letters as well as words