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

Iulia Maria Lungu
Iulia Maria Lungu
17,546 Points

Not expected output

My solution for this task is

# 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(str):
    dictionary = {}
    chunks = str.lower().split()
    for word in chunks:
        try:
            dictionary[word] += dictionary[word]
        except KeyError:
            dictionary[word] = 1
    return dictionary

print(word_count("I do not like it Sam I Am"))
# and the output is {'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1}

Why i can't pass the challenge? I see the order is not the same. How are the tests made for this challenge? I am confused. What am i doing wrong? Thanks

1 Answer

Steven Parker
Steven Parker
231,275 Points

You're pretty close, but there's an issue on this line:

            dictionary[word] += dictionary[word]

This will double the count, but you only want to increase it by 1.

Also, for the challenge you only need to create the function. You don't need to call it or to print anything.

Iulia Maria Lungu
Iulia Maria Lungu
17,546 Points

Thanks, mate. Stuff done late at night is always bad. Of course this += dictionary[word] was the issue. I should have added just 1 for the new occurrence! Having just that test I did not realize my error! And the function call was there just to show the output.