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 trialJack Mansager
14,551 PointsWord Count Challenge Problem. My code works fine in python IDE but won't pass challenge
Any help with this would be awesome!
Jack Mansager
14,551 Pointsdef word_count(sentence):
lower_sentence = sentence.lower()
list = lower_sentence.split()
my_dict = {}
for items in list:
count = 1
if items in my_dict:
count += 1
my_dict[items] = count
return my_dict
word_count("I am that I am")
3 Answers
Chris Freeman
Treehouse Moderator 68,454 PointsYour are accumulating count
across all items. Instead increment count for each item as needed:
def word_count(sentence):
lower_sentence = sentence.lower()
list = lower_sentence.split()
my_dict = {}
for items in list:
if items in my_dict:
my_dict[items] += 1
else:
my_dict[items] = 1
return my_dict
Attila Farkas
9,323 PointsHi Jack, the problem with your code is the way you update an existing dictionary item when a word is found more than once. The updated dictionary value for such a key is always 2 since your 'count' variable is reset to 1 for each iteration of the for loop. Your code works for a sentence that has no more than two instances of any word, but breaks otherwise. I hope this points you in the right direction to fix the problem.
Jack Mansager
14,551 PointsThanks for your help! With your help I now understand how to make it work.
Jack Mansager
14,551 PointsJack Mansager
14,551 PointsBelow is my code