Python Python Collections (2016, retired 2019) Dictionaries Word Count

Derick Ho
Derick Ho
3,113 Points

I have another working solution that solves the given problem but it still tells me that it is incorrect!

You may copy the code and see that it works! The task is to take a string and use the contents as the key to a dictionary and the number of of times an item appears as the value. My code does exactly that and yet the problem tells me it is wrong.
# 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(word):
    words = []
    dictionary = {}
    word = word.lower()
    words = word.split(' ')
    unique_words = []
    for item in words:
        if item not in unique_words:
            count = 1
            dictionary[item] = count
        elif item in unique_words:
            count += 1
            dictionary[item] = count
    return dictionary

2 Answers

Hello Derick,

Your code is correct, just replace your split.(' ') with split() and you are ready to go.

I allowed my self to write a more efficient code for you, eliminating some unnecessary steps in your code.

def word_count(string):
    dictionary = {}
    words = string.lower().split()
    for word in words:
        if word not in dictionary:
            dictionary.update({word : 1})
            dictionary[word] += 1
    return dictionary

which error it gives u