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

code gave an error in the test but works in the workspace

the code below is what I wrote for the challenge, it gives an error saying that it didn't give the expected output which is supposed to be

{'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1}

if I use the string "I do not like it Sam I Am"

however, using the same code in the treehouse workspace prints exactly what is desired. I literally copy pasted the code with the exception that I use print function in the workspace to print the dictionary to check if the output I get is same as what I wanted.

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):
    lower_case_string = string.lower()
    string_array = lower_case_string.split(" ")
    string_dict = {}
    for word in string_array:
        if word in string_dict.keys():
            string_dict[word] += 1
        else:
            string_dict[word] = 1
    return string_dict

1 Answer

This one is a bit of a trick question. Your function breaks if there is additional whitespace between any of the words in the string.

Example:

#function
word_count("I\t  \n do not like it Sam I Am")
#result
{'i\t': 1, '': 1, '\n': 1, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'i': 1, 'am': 1}

So you'll need to remove ALL whitespace between each word in the string.

Oh!! completely slipped my mind. It makes sense. Thanks, Kyle.