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

Tyler Shand
seal-mask
.a{fill-rule:evenodd;}techdegree
Tyler Shand
Python Web Development Techdegree Student 15,043 Points

Code Works But Not Passing Challenge

When I run this code on my computer it runs as specified by the instructions but when I run it on Treehouse it fails. 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):
    string = string.lower()
    word_counter = {}

    # Split 'string' into a list
    string_list = string.split(' ')

    # Give all words keys in 'word_count'
    for item in string_list:
        word_counter[item] = 0

    # Assign the number of times a word appears to it's dictionary key value
    for item in string_list:
        word_counter[item] += 1


    return word_counter

1 Answer

Chris Howell
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Chris Howell
Python Web Development Techdegree Graduate 49,702 Points

Hi Tyler Shand

So I ran your code, it looks like you are getting this error message:

Bummer! Hmm, didn't get the expected output. Be sure you're not splitting only on spaces!

this is inferring that in your code

def word_count(string):
    string = string.lower()
    word_counter = {}

    # Split 'string' into a list
    string_list = string.split(' ') # Problem here.

    # Give all words keys in 'word_count'
    for item in string_list:
        word_counter[item] = 0

    # Assign the number of times a word appears to it's dictionary key value
    for item in string_list:
        word_counter[item] += 1


    return word_counter

You are capturing spaces only, but need to capture all the different types of whitespace ("spaces, tabs, breaks, etc")

Python Docs: Split