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

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

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

Not sure what you are doing in the line:

count = copy[item] + 1

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

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

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

Ohh I see, ok. Thanks for the answer