Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.

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(string):
    dic=dict()
    string=string.lower()
    string=string.split(' ')
    for x in string:
        count=1
        if x in dic.keys():
            count=dic[x]+1
        dic[x]=count
    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.