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

Scott Dunstan
Scott Dunstan
12,517 Points

Result as expected but code not accepted

The example string, and many other example strings came out as expected with this code:

def word_count(sentence):
    keys_list = sentence.lower()split(' ')
    new_dict = {}
    for word in keys_list:
        new_dict[word] = keys_list.count(word)
    return new_dict

example string given was: "I do not like it Sam I Am"

so my code is called like this: word_count("I do not like it Sam I Am")

and produces this: {'am': 1, 'do': 1, 'i': 2, 'not': 1, 'it': 1, 'like': 1, 'sam': 1}

but it doesn't pass. The error message was "Hmmm, didn't get what I expected", but it is exactly what I expected! Can anyone see where I've gone wrong?

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(sentence):
    keys_list = sentence.lower()split(' ')
    new_dict = {}
    for word in keys_list:
        new_dict[word] = keys_list.count(word)
    return new_dict

3 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there! You're doing great, but there's part of the instructions that you're missing and I'm guessing you've only tested data sets that don't include this corner case. The challenge asks you to split the string on all whitespace. But currently you're only splitting on spaces. This does not account for whitespace such as tabs or new lines. Also, your code is missing a period/full stop between the .format() and split.

To fix this, your split should be used without any arguments. Take a look at your edited line:

keys_list = sentence.lower().split()

This will do the same thing as your code, but split on all whitespace instead of just spaces.

Hope this helps! :sparkles:

Scott Dunstan
Scott Dunstan
12,517 Points

Never mind, I found the problem.

  1. I missed the "." for "split()"
  2. I had a literal space "split(' ')" instead of whitespace: ".split()" These dictionary challenges have messed me up
Scott Dunstan
Scott Dunstan
12,517 Points

Thanks Jennifer, Just posted that as you posted yours!