Python Python Collections (2016, retired 2019) Dictionaries Word Count

Artur Owczarek
Artur Owczarek
2,995 Points

Error for valid output (dictionaries)

I wrote the code you can see below. For me it works fine, but I get an error (Bummer: Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!). I think it is fine because I ran this code in PyCharm for example it is written in comments and I got good output.

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(statement):
    words_in_statement = statement.lower().split(sep=' ')
    my_dictionary = {}
    for word1 in words_in_statement:
        word_counter = 0
        for word2 in words_in_statement:
            if word1 == word2:
                word_counter += 1
        my_dictionary[word1] = word_counter
    return my_dictionary

1 Answer

Steven Parker
Steven Parker
171,327 Points

The clue is the message about "splitting on all whitespace". To make the "split" function work on "all whitespace", you either leave the argument empty or set it to None.

Giving it an explicit space argument causes a different behavior (thought it was probably appropriate for the way you were testing it).

camberden
camberden
1,672 Points

Thanks so much for this answer! It's true that using (' ') wouldn't account for all instances of whitespace in the input; this was where my code was falling short as well.