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

Dan Morse
Dan Morse
6,095 Points

Getting the right output on my machine...

Greetings gurus and fellow learners! 😁 I'm getting the right output when I run my code, at least the sample sentence matches up perfectly. I'm not sure why I'm getting the feedback that the output isn't right. Any thoughts?

Thanks for your help!

Here's my output: {'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1}

# 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(text):
    actual_count = {}
    text = text.lower()
    words = text.split(" ")
    for word in words:
        if word not in actual_count.keys():
            actual_count.update({word: 1})
        elif word in actual_count.keys():
            actual_count[word] += 1
    return actual_count

1 Answer

28,558 Points

The challenge wants you to split on all whitespace. Your code splits on spaces, which is a type of whitespace, but there are lots of other characters considered whitespace. Like line breaks, tabs, and other things like that.

The code works on the example input since that only uses spaces, but the example input the challenges shows you is often different from the value they actually pass to the function. They often differ in order to make it harder to cheat the challenge checker by hardcoding your return to the right values.

Conveniently enough the split method actually splits on all whitespace by default, so if you remove the argument from your split method like this:

words = text.split()

Then your code will work.

Dan Morse
Dan Morse
6,095 Points

Awesome! Thank you! I tried all different strings, but couldn't find one that didn't work. Obviously, I didn't try a string with a line break in it... Anyway, thanks again!