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

I can't complete wordcount challenge due to the odd bammer.

I tried to launch my code in IDE. All requirements passed. But i still have a bammer error ("Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!"). What should i do with my code to move forward in correct way? Thanks.

My code:

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(phrase):
    word_list = phrase.lower().split(' ')
    dictionary = dict.fromkeys(word_list)
    keys = dictionary.keys()
    for i in keys:
        counter = 0
        for z in word_list:
            if z == i:
                counter += 1
            else:
                continue
        dictionary[i] = counter
    return dictionary
word_count(phrase='I do not like it Sam I Am')

2 Answers

Steven Parker
Steven Parker
231,269 Points

:warning: Be careful about testing a challenge in an external REPL.
If you have misunderstood the challenge, it's also very likely that you will misinterpret the results.

The challenge said to "Be sure you're ... splitting on all whitespace". But if you pass a space as an argument to split, it will only split on spaces (and on every space). To split on "all whitespace" you leave the argument empty.

Steven Parker, Good catch. This tripped me up as I come from a JavaScript background where the default isn't on whitespace. I up-voted you and hopefully you get answer credit!

Here's my solution since I'm here:

def word_count(words):
    output = {}
    for word in words.split():
        lower = word.lower()
        if lower not in output:
            output[lower] = 1
        else:
            output[lower] += 1
    return output
Steven Parker
Steven Parker
231,269 Points

It's always great when I can help more than one student with an answer.

Steven Parker, Thanks for your rapid answer. Now all things is clear. I'll keep in mind this feature of split method. My code passed the challenge.