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

Jose Camilo
Jose Camilo
7,031 Points

My code works on another python environment. but not here. Wonder why..

def word_count(word):

word = word.lower()
words = word.split()    
copy = {}
count = 1
for item in words:
  for key in copy.keys():
      if item == key:
          count = count + 1
  copy[item] = count

return copy

print(word_count("I like my Mom like"))

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(word):

    word = word.lower()
    words = word.split()    
    copy = {}
    count = 1
    for item in words:
        for key in copy.keys():
            if item == key:
                count = count + 1
        copy[item] = count

    return copy

3 Answers

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,941 Points

I also made count increment the previous count. The modified code below passed the challenge.

def word_count(word):
    word = word.lower()
    words = word.split()    
    copy = {}
    count = 1
    for item in words:
        count = 1
        for key in copy.keys():
            if item == key:
                count = copy[item] + 1
        copy[item] = count

    return copy
Jose Camilo
Jose Camilo
7,031 Points

Not sure what you are doing in the line:

count = copy[item] + 1

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,941 Points

Try the example "I do not like it Sam I Am". You'll see 'am' : 2 because count doesn't reset.

Jose Camilo
Jose Camilo
7,031 Points

Yep, forgot to reset the count, since I left it out of the loop but still not working.

KRIS NIKOLAISEN
PRO
KRIS NIKOLAISEN
Pro Student 51,941 Points

If an item exists count = copy[item] + 1 updates the count to the current count + 1. I think this code is a little clearer:

def word_count(word):
    word = word.lower()
    words = word.split()    
    copy = {}

    for item in words:
        if item in copy.keys():
            copy[item] = copy[item] + 1
        else:
            copy[item] = 1
    return copy
Jose Camilo
Jose Camilo
7,031 Points

Ohh I see, ok. Thanks for the answer