Python Python Collections Dictionaries Word Count

Nick B.
Nick B.
Front End Web Development Techdegree Student 4,801 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

adrian miranda
adrian miranda
9,879 Points

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.

Nick B.
Nick B.
Front End Web Development Techdegree Student 4,801 Points

I tested my function as you said and I see what you mean now. Thanks Adrian!