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 trialChenai Chitakunye
2,308 Pointsword_count
Please help me understand what I've done wrong!
# E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.
def word_count(singles):
singles = singles.lower()
second = singles.split()
dict = {}
for words in singles:
dict[words] = singles.count(words)
return dict
1 Answer
Louise St. Germain
19,424 PointsHello Chenai,
You're very close!
To fix the problem, you need to loop through your second variable, which you created using the split() method on singles, since this is what contains all the individual words in the sentence. This needs to be changed in both the line with "for" and the line inside the for loop. So your code should look like this:
def word_count(singles):
singles = singles.lower()
second = singles.split()
dict = {}
# Use second instead of singles here, because second contains
# all the individual words. Otherwise, it loops through singles
# letter by letter, which is not what you want
for words in second:
dict[words] = second.count(words)
return dict
That's all that needs to be fixed! Hope this helps!