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

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.

# 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
218,815 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
218,815 Points

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