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

Woongcheol Yang
Woongcheol Yang
5,605 Points

wordcount.py

What's problem?

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

2 Answers

Nothing in particular, but try split() rather than split(' ').

It should be working fine but i guess, its some kind of bug in the site.

# 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):
    words = string.lower().split()
    res = {}
    for word in words:
        if word in res.keys():
            res[word] += 1
        else:
            res[word] = 1
    return res
Stuart Wright
Stuart Wright
41,119 Points

I've seen a few people have the same problem with this challenge. Your code will pass the challenge if you pass no arguments to the .split() method. This is because by default this method splits on all whitespace, and there is more than one type of whitespace character (the ' ' that you passed is just one of them, so your code won't split on other kinds of whitespace character - tabs for example).

def word_count(string):
    words = string.lower().split()  # <-- No arguments passed
    res = {}
    for word in words:
        if word in res.keys():
            res[word] += 1
        else:
            res[word] = 1
    return res