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

Nick B.
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Nick B.
Full Stack JavaScript Techdegree Graduate 31,101 Points

Word Count Code Challenge Help Needed!

Could anyone help me out please? My code runs just fine in Idle, but it doesn't seem to be working here.

string = "I do not like it Sam I Am"

def word_count(string): dict = {} split_word = string.lower().split(" ") for item in split_word: value = split_word.count(item) dict[item] = value return dict

print(word_count(string))

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.

string = "I do not like it Sam I Am"

def word_count(string):
    dict = {}
    split_word = string.lower().split(" ")
    for item in split_word:
        value = split_word.count(item)
        dict[item] = value
    return dict

print(word_count(string))

1 Answer

I think you might be being overly specific. You are calling split with an argument of a " ". You should look this up, but when split is called without an argument, it will automatically split on any white space (eg it will also split on a tab), and it will also remove any empty strings. No, the instructions aren't very specific, but if you think about it, it probably makes more sense to split on tabs, as well as to remove empty strings.

If you want to test your function, try a sentence that has multiple spaces between words, and/or with tabs.