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
Devin Scheu
66,191 PointsHelp With Python :)
Okay i seriously stumped
Question: 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.
Answer:
def word_count(word):
string_dict = {}
for word in split_string:
if string_dict[word]:
string_dict[word] += 1
else:
string_dict[word] = 1
Kenneth you've stumped me good. With no other forms giving me a clear answer to this challenge I've scrambling around hours for the right answer. And if my code looks the way i feel it is i think i have several errors .
1 Answer
Stone Preston
42,016 Pointsfor one, you never split the string. try splitting it first and then see what you can figure out. also I would change the name of the parameter since you use word in the for loop:
def word_count(sentence):
string_dict = {}
split_string = sentence.split()
for word in split_string:
if string_dict[word]:
string_dict[word] += 1
else:
string_dict[word] = 1
also note that if string_dict[word]: is going to throw an exception if the key does not already exist in the dictionary, so you are going to have to change that.
you might try using the in keyword, which would test if a given key is already in the dict. dont forget to return the dictionary at the end:
hint:
#this will test if the key is already in the dict or not
if word in string_dict:
#key is already in the dictionary, so increment its value
else:
#key is not in the dict yet, set its value to 1