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

Harris Handoko
Harris Handoko
3,932 Points

word_count challenge task not working correctly: it works on workspace, but it didn't pass the checker

Adding the following to call the function:

string = "I do not like it Sam I Am"
print(word_count(string))

I got:

['i', 'do', 'not', 'like', 'it', 'sam', 'i', 'am']                                         
{'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1}

Please tell me where I went wrong?

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):
    word_list = (string.lower()).split()
    print(word_list)
    word_count = {}
    for word in word_list:
        count = 1
        try:
            if word_count[word] >= 1:
                word_count[word] = count + 1 
        except KeyError:
            word_count[word] = count
    return word_count

1 Answer

Renato Guzman
Renato Guzman
50,301 Points

Try testing with: "I like people, I like pets and I like ice cream". Notice that count is always 1 in every iteration. Also I recommend to change the name of your variable word_count since it is the same as your method. Hope it helps!

Harris Handoko
Harris Handoko
3,932 Points

Thanks! count = 1 was not correct, how could I forget the age-old += 1 ?!!! ;)

def word_count(string):
    word_list = (string.lower()).split()
    print(word_list)
    word_count = {}
    for word in word_list:
        try:
            if word_count[word] >= 1:
                word_count[word] += 1 
        except KeyError:
            word_count[word] = 1
    return word_count

string = "I like people, I like pets and I like ice cream"
print(word_count(string))