Python Python Collections Dictionaries Word Count

William Sserubiri
William Sserubiri
1,933 Points

Hey there, my attempted solution for this problem ```word_count("I do not like it Sam I Am")``` failed please advise

I have tried testing out my solution in many other apps and it works flawlessly. I am not sure what I am missing in my function

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):
    lower_string = string.lower()
    string_list = lower_string.split(" ")

    final = {}
    count = 1
    for word in string_list:
        if word in final.keys():
            final[word] =  count + 1
        else:
            final[word] =  count

    return final

2 Answers

Steven Parker
Steven Parker
168,104 Points

Perhaps you're testing with "lucky" data. The "Bummer" message gave you a hint: "Be sure you're lowercasing the string and splitting on all whitespace!" To split on "all whitespace" the argument to "split" should be left empty or set to None.

Also, it looks like "count" will continue to grow as the loop runs, but a new entry should always have the value set to 1, and an existing one should be incremented by one from its own current value.

William Sserubiri
William Sserubiri
1,933 Points

Thanks, Steven but I have tried to make some modifications but it still fails

def word_count(string):
    lower_string = str(string)
    lower_string = lower_string.lower()
    string_list = lower_string.split(" ")

    final = {}
    count = 1
    for word in string_list:
        if word in final.keys():
            final[word] =  final[word] + 1
        else:
            final[word] =  1

    return final


print(word_count("I do not like it Sam I Am"))
William Sserubiri
William Sserubiri
1,933 Points

Thanks, Steven I have solved it

def word_count(string):
    lower_string = str(string)
    lower_string = lower_string.lower()
    string_list = lower_string.split()

    final = {}
    count = 1
    for word in string_list:
        if word in final.keys():
            final[word] =  final[word] + 1
        else:
            final[word] =  1

    return final


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