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 trialJose Camilo
7,031 PointsMy 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"))
# 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
54,972 PointsI 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
KRIS NIKOLAISEN
54,972 PointsTry the example "I do not like it Sam I Am". You'll see 'am' : 2 because count doesn't reset.
Jose Camilo
7,031 PointsYep, forgot to reset the count, since I left it out of the loop but still not working.
KRIS NIKOLAISEN
54,972 PointsIf 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
7,031 PointsOhh I see, ok. Thanks for the answer
Jose Camilo
7,031 PointsJose Camilo
7,031 PointsNot sure what you are doing in the line:
count = copy[item] + 1