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 trialWarren Chisasa
3,731 PointsAdding keys to dictionaries
I am trying to add a key and and the number of times it appears in a string. But the issue is, I am getting a 'bummer!' and the warning is that 'some words are missing'. I am sure the problem is with the for loop but I couldn't find a way wrapping my head around the problem. Asking for help.
# E.g. word_count("I am that I am") gets back a dictionary like:
# {'i': 2, 'am': 2, 'that': 1}
# Lowercase the string to make it easier.
# Using .split() on the sentence will give you a list of words.
# In a for loop of that list, you'll have a word that you can
# check for inclusion in the dict (with "if word in dict"-style syntax).
# Or add it to the dict with something like word_dict[word] = 1.
def word_count (my_str): # function to return string as key and value
word_dict = {}
my_str.lower()
my_str.split()
count = 1
for word in my_str: #iterate to add key and number of times it appears to dictionary
word_dict[word] = count
count +=1
return word_dict
1 Answer
wang yang
Courses Plus Student 1,728 Pointsdef word_count(sentence):
my_dict = {}
sentence_lower = sentence.lower()
for word in sentence_lower.split():
value = sentence_lower.count(word)
my_dict[word] = value
return my_dict
didn't work too! says "Didn't get the right count for some of the words."
wang yang
Courses Plus Student 1,728 Pointswang yang
Courses Plus Student 1,728 Pointsthis worked! but i don't know why i must put word in list
Warren Chisasa
3,731 PointsWarren Chisasa
3,731 PointsThanks! the second code worked!