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 trialbeven nyamande
9,575 Pointsiteration in dictionaries
getting bummer ! some words missing where am i getting it wrong
# 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(sentence):
my_dict={}
for word in sentence.split():
if word in my_dict.keys():
my_dict[word] +=1
else: my_dict[word] = 1
return my_dict
1 Answer
Chris Shaw
26,676 PointsHi Beven,
You have a couple of issues with your code.
You are using inconsistent spaces and indentation, your
else
statement should be on it's own line andreturn
should be in the same indent column asfor
my_dict.keys()
isn't required, all we need to do is simply check if the word is in the dictionary already.
def word_count(sentence):
words = {}
for word in sentence.split():
if word in words:
words[word] += 1
else:
words[word] = 1
return words
One thing you will notice is I changed my_dict
to words
, I prefer to use self explanatory variable names which help others understand your code easier.
Happy coding.
beven nyamande
9,575 Pointsbeven nyamande
9,575 Pointsstill keep getting bummer!"some words missing"
Chris Shaw
26,676 PointsChris Shaw
26,676 PointsWorks fine from my end, not to sound to forthright but are you sure to copied the code correctly?
beven nyamande
9,575 Pointsbeven nyamande
9,575 Pointsoh thanks chris saw its to do with indendation