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

David Luo
David Luo
1,215 Points

word_count: code works on my IDE, but having error. I know it's something small somewhere but can't seem to debug this!

Well, I found a few ways to approach this that I thought would have worked, but unfortunately getting an error. This code works for the test case on my IDE, but can't seem to pass this on the Treehouse workspace.

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(str):
    words_list = str.lower().split(" ")
    # defaulting dictionary with corresponding words as keys and 0 for values
    # d = dict(zip(words_list,[0]*len(words_list)))
    d = dict.fromkeys(words_list, 0)
    # iterate and count 
    for word in words_list:
        d[word] += 1
    return d

2 Answers

andren
andren
28,558 Points

The problem is that the challenge wants you to split on all whitespace. You are currently splitting on single spaces, and while that is an example of whitespace it is far from all. Multiple spaces, line-breaks, tabs and so on are also examples of whitespace, which won't get split based on your code.

Luckily the solution is actually quite simple. The split method splits on all whitespace by default if you don't provide it with an argument. So the solution to this issue is to simply remove the argument you pass it. Like this:

def word_count(str):
    words_list = str.lower().split()
    # defaulting dictionary with corresponding words as keys and 0 for values
    # d = dict(zip(words_list,[0]*len(words_list)))
    d = dict.fromkeys(words_list, 0)
    # iterate and count 
    for word in words_list:
        d[word] += 1
    return d
David Luo
David Luo
1,215 Points

Andren, thanks again. so many subtle points to consider!