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 trialMUZ141005 Ronald Maravanyika
3,148 PointsCreate a function named word_count() that takes a string. Return a dictionary with each word in the string as the key an
where am l getting this wrong.'i' whats that??
# 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.
a_string="I am that I am"
a_stringsplit=(a_string.lower()).split()
def word_count(a_string):
string_dict={}
for word in a_stringsplit:
if string_dict[word]:
string_dict += 1
else:
string_dict[word] = 1
return string_dict
1 Answer
Vittorio Somaschini
33,371 PointsHello Ronald.
You are not too far but still I see a few mistakes here.
Please note that you do not need to hard code the string itself, it will automatically be provided to the compiler. So get rid of the 2 lines outside the function.
Then, inside the for loop, you will need to go through the list we get when splitting the string. So something like for word in a_string.split() would do.
Lastly the if statement needs to check if the word is in the dictionary, so "if word in string_dict:" Also, please note that in both cases (if and else) what we need to target is the right key in the dictionary, so in both cases we would go with string_dict[word] like you did in the else statement.
These little changes should do the trick, let me know if you manage to pass the test!
;)
Vittorio
MUZ141005 Ronald Maravanyika
3,148 PointsMUZ141005 Ronald Maravanyika
3,148 Pointsthank you Vittorio.l passed the test but they is a part l did not understand:what about the lowercase issue??
Vittorio Somaschini
33,371 PointsVittorio Somaschini
33,371 PointsOh right.
I think you can just use .lower() on the string before splitting it.
;)