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

Ken LaRose
seal-mask
.a{fill-rule:evenodd;}techdegree
Ken LaRose
Python Web Development Techdegree Student 21,982 Points

Python word_count function isn't passing - what's wrong?

I wrote this word_count function to accept a string and return a dictionary filled with the lowercase version of each word and the integer count of each word in the original string. I can't pass the code challenge, but every string I send through this function comes out right... I think... Can anybody see what's wrong with this solution?

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

1 Answer

I think this line might be your problem: arg.lower().split(' '), which should probably just be arg.lower().split().

The reason for this is that splitting a string on spaces would treat a double space as a word, whereas calling .split without an argument will ensure empty spaces are all trimmed.

Yeah, that was pretty subtle; glad it worked :D