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

Ekata Singh
Ekata Singh
2,872 Points

Code does not Work

This Code seems to work in the workspace but not here.

# 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):
    string=string.split(' ')
    for x in string:
        if x in dic.keys():
    return dic

2 Answers

I pasted in your code in the challenge and got "Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!" (my emphasis). You're currently splitting on one space ' '. If you had a string like:

 "hey    i'm   a     string   with    a   lot   of   spaces"

it would split on one space so you'd actually get ' ' as a word (with a bunch of "count"). Just use the default split() without any arguments. That will split words on all whitespace so you only get a list of words.

Ekata Singh
Ekata Singh
2,872 Points

Oops! Didn't take that scenario into account.The code works now.

Thanks a ton! :)

When you paste code from workspace or someplace else, sometimes it won't pass the challenge even if it's correct. Try typing it in.

Ekata Singh
Ekata Singh
2,872 Points

Tried that too! Still doesnt work.