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

Really struggling with this part of the Python course!!

I can't seem to understand why this short code isn't working!! If anyone could quickly look at it and say why would be really helpful - thanks. Alex

word_count.py
string = "I am that I am"
my_dict = {}

def word_count(string):
    my_list = string.lower().split()
    for word in my_list:
        if word in my_dict:
            count += 1
            my_dict[word] = count
        else:
            my_dict[word] = 1
    return(my_dict)

1 Answer

Robin *
Robin *
5,670 Points

you forgot the define the count variable

for word in my_list:
    count = 1
    if word in my_dict:
        count += 1
        my_dict[word] = count
    else:
        my_dict[word] = count