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

word_count function works in Terminal but not passing in Treehouse challenge

This code works in Terminal, but it's not passing the challenge. Suggestions appreciated!

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.
count_dict = {}

def word_count(sentence):
    sentence = sentence.lower()
    words = sentence.split()
    for word in words:
        if word == " " or word in count_dict:
                continue
        else:
            count = words.count(word)
            # add character and count to the dictionary?
            count_dict[word] = count
            #if character already in dict, skip
    print(count_dict)

word_count("I do not like it Sam I Am")

3 Answers

Steven Parker
Steven Parker
231,269 Points

The challenge says that your function should return the final dictionary. You don't need to "print" anything.

Also you only need to define the function, not call it (the validation system does that).

That worked! Thank you, Stephen!

I also have the same issue. function is working on my local python but not on challenge.

my version is:

def word_count(sentence):
    words = sentence.lower().split(' ')
    dict_count = {}
    for word in words:
        if word in dict_count.keys():
            dict_count[word] += 1
        else:
            dict_count[word] = 1
    return dict_count

and the local test:

dict_test = word_count("I do not like it Sam I Am")
dict_test
{'i': 2, 'do': 1, 'not': 1, 'like': 1, 'it': 1, 'sam': 1, 'am': 1}
Steven Parker
Steven Parker
231,269 Points

Your error message contains a hint: "Bummer! Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!"

To split on "all whitespace", the call to "split" should have no argument. Supplying a space argument causes it to split only on explicit space characters.

Thank you Steven. It worked! However, I still do not understand why the local python accepts the split(' ')

Steven Parker
Steven Parker
231,269 Points

You probably only tested it with the sample. The actual validation uses multiple passes with other data.