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 trialGary Law
14,632 PointsCannot pass Python stage 3 - Dictionaries Challenge Task 1
I dont know why the following code not working? Anyone can help? Thanks a lot.
def word_count(my_string):
my_dict = {}
my_list = my_string.lower().split()
for item in my_list:
if item in my_dict:
my_dict[item] = my_dict[item] +1
else:
my_dict[item] = 1
Gary Law
14,632 PointsThanks Kenneth!
1 Answer
Chris Shaw
26,676 PointsHi Gary,
I've outlined a couple of points below.
- You can use the increment operator to increase the number count for the dictionary key
- You aren't returning your dictionary once the
for
loop has being completed.
I've slightly modified your code just to make it clearer what's happening.
def word_count(words):
my_dict = {}
words = words.lower()
for word in words.split():
if word in my_dict:
my_dict[word] += 1
else:
my_dict[word] = 1
return my_dict
Gary Law
14,632 PointsHi Chris, thanks so much for your help!
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherThe only problem with your code is that you didn't return
my_dict
at the end.But I see a place where I need to improve the code challenge, so thanks! (check your badges for something special)