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

Ian Cole
Ian Cole
454 Points

Dictionary Word_Count Problems

So I don't understand how this is not passing. I run this outside of the challenge and it does exactly what it's supposed to, separates at all the whitespace and lowercases the output.

# 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_string = string.lower()
    split_string = lower_string.split(" ")
    word_dict = {}
    for word in split_string:
        if word in word_dict:
            word_dict[word] += 1
            word_dict[word] = 1
        word_count = word_dict
    return word_count                                                                                                                                                                                       

1 Answer

Alex Koumparos
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Ian,

The problem is with how you are splitting the string. You are using the argument " " which is fine if you know that the string is going to have single whitespace spacing. If you don't know that, and there is the possibility that there could be double spaces (or some other multiple) or other whitespace characters (e.g., tabs) then you could end up with an array that's not what you expect.

For example, your use of split would turn "hello world" into ["hello", "", "world"] and "hello\tworld" into ["hello\tworld"]. Although the text of the challenge doesn't expressly state that you might get strings of words that are spaced with something other than single space characters, the parser does give a hint when it tells you, "didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!".

To split on all whitespace instead of single spaces, you just use the split method without any arguments. So "hello world".split() and "hello\tworld".split() will both produce ["hello", "world"].

Hope this clears everything up for you.



Ian Cole
Ian Cole
454 Points

Thanks, it worked! I actually didn't know that was how white-space was handled.