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

Shahid Mohamed Islam
Shahid Mohamed Islam
4,371 Points

Code not passing. Works fine in workspace. Why is this the case?

If my code is wrong I'd appreciate an example of a string that wouldn't pass.

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):
    dictionary = {}
    split_string = (string.lower()).split(' ')
    for key in split_string:
        dictionary[key] =  split_string.count(key)
    return dictionary

2 Answers

Steven Parker
Steven Parker
231,236 Points

You're probably not testing as rigorously as the challenge does. In particular, the challenge wants to be sure your function will work with any combination of "white space", but splitting on an explicit space won't do that.

Instead, either leave out the argument completely ("split()") or pass "None" ("split(None)").

And "Here is an example       string that       might not pass".

The error message you receive is: Bummer: Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!

To split on all whitespace pass an empty string to split:

split_string = (string.lower()).split('')
Steven Parker
Steven Parker
231,236 Points

You've got the right idea, but an empty string doesn't do it either. See my answer for two ways that will.