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

Challenge won't complete but my code works on Python

The challenge is to take a string, split it and return a dictionary with the keys of the words of the string and the values of how many times the words were in that string. My code returns a dictionary just like that in the challenge but it doesn't verify as correct. What am I doing wrong?

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):
    # Vending MachineSSS
    string = string.lower()
    words = string.split(' ')
    dictionary = dict()
    for word in words:
        try:
            dictionary[word] += 1
        except KeyError:
            dictionary[word] = 1
    return dictionary

1 Answer

Steven Parker
Steven Parker
231,269 Points

You're really close there! The "Bummer" message you get contains a hint: "Be sure you're lowercasing the string and splitting on all whitespace!"

To split on "all whitespace", the argument to the "split" function should be left empty. Providing a literal space causes it to split at each individual space character.

Thank you! I didn't realize exactly what the term 'all whitespace' meant but now I do.

Thank you, Steven Parker, for the info on the split(). That helped.