Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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