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 getting correct output for dictionary within work-space, put not passing the challenge.

Hi

Within the work-space python shell the script runs fine. The function returns the correct keys and number for each key within the dictionary and all letters are lowercase. But it will not pass the challenge.

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):

    dict_count = {}

    string_list = (string.lower()).split(' ')

    for item in string_list:  
        if item not in dict_count:
            dict_count.update({item:1})
        else:
            dict_count[item] += 1

    return dict_count

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,426 Points

You are so close! Split the string on Whitespace (the default with no argument) rather than splitting on a literal Space.

Also, there is an unnecessary set of parens in the line:

string_list = (string.lower()).split(' ')

# should be

string_list = string.lower().split(' ')

Awesome! Thanks so much Chris! Why did splitting on a literal space cause an error?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,426 Points

The test input could use Tabs or multiple spaces to delimit the words. Using Whitespace covers all these cases.

Ah i see, that makes sense. Thanks