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
otarie
984 PointsPlease help with simple challenge question re: lists and dictionaries
I'm a bit rusty since I haven't coded for 2 weeks. Can someone please help me with the following challenge? The code I have so far is beneath. Many thanks!
Create a function named word_count() that takes a string. Return a dictionary with each word in the string as the key and the number of times it appears as the value.
def word_count(x):
new_list = x.split()
my_dict = []
for word in new_list:
my_dict[word]=1
3 Answers
Vittorio Somaschini
33,371 PointsHello Otarie and Greg.
I think that Greg explained the problems in your code pretty well and for sure you (Otarie) need to correct those in order to make it work.
Greg's code does the right job, but it may be a little be tricky to understand; so I thought you may want to have a look at this other piece of code; the only difference is that it uses a if statement instead of 2 for loops, so you may find it more readable.
I thought it was good to paste this as it may give you a clearer idea how what goes on behind the scenes in the double for loop:
def word_count(x):
new_list = x.split()
my_dict = {}
for word in new_list:
if word in my_dict:
my_dict[word] += 1
else:
my_dict[word] = 1
return my_dict
I hope it helped as well as Greg's answer! ;)
Vittorio
Greg Kaleka
39,021 PointsHi otarie,
- You've got the split working right.
- Your dictionary declaration needs curly braces not square brackets.
- Your function sets the value of each key to 1, so they can never go any higher!
- Your function doesn't return anything.
Here's my solution:
def word_count(x):
new_list = x.split()
my_dict = {}
for word in new_list:
my_dict[word] = 0
for word in new_list:
my_dict[word] += 1
return my_dict
otarie
984 PointsThanks guys, this definitely helps - and yes, Vittorio, your code is easier to understand!!
Greg Kaleka
39,021 PointsGreg Kaleka
39,021 PointsNice - my Python's a bit rusty. I like your solution.