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

Word_count issue. My test cases worked but in the challenge, it doesn't get the correct answer.

I have the following code:

def word_count(string): string = string.lower() list_string = string.split(" ") key_items = {} for word in list_string: key_items[word] = list_string.count(word) return(key_items)

When I tried to test, it comes out correctly... Is there anything I am missing?

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()
    list_string = string.split(" ")
    key_items = {}
    for word in list_string:
        key_items[word] = list_string.count(word)
    return(key_items)

1 Answer

andren
andren
28,558 Points

Your code is very close, but the challenge wants you to split on all whitespace. Your code splits on spaces, which is a type of whitespace, but there are lots of other characters considered whitespace. Like line breaks, tabs, and other things like that.

The code works on the example input since that only uses spaces, but the example input the challenges shows you is often different from the value they actually pass to the function. They often differ in order to make it harder to cheat the challenge checker by hardcoding your return to the right values.

Conveniently enough the split method actually splits on all whitespace by default, so if you remove the argument from your split method like this:

list_string = string.split()

Then your code will work.