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
203,700 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
203,700 Points

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