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 trialMark Ramos
19,209 Pointsword_count Challenge
My code below seems to work OK in Workspace, but doesn't pass the challenge. Any idea what I've got 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(string):
dict = {}
count = []
words = string.lower().split(" ")
for word in words:
dict[word] = words.count(word)
return dict
Mark Ramos
19,209 PointsHey Steven - the line you referred to is a way to add a new key and value to a dictionary. For example:
>>> my_dict = {'a': 1, 'b': 2}
>>> print(my_dict)
{'a': 1, 'b': 2}
>>> my_dict['c'] = 3
>>> print(my_dict)
{'a': 1, 'b': 2, 'c': 3}
So 'dict' was just calling my empty dictionary from earlier in the block and [word] was me adding new keys to dict, one for every word in words. I hope that is helpful!
Steven Olick
1,561 PointsSO helpful. Thanks for breaking that down for me!!
1 Answer
Unsubscribed User
9,496 Pointsuse split with no arguments, and it will split at the whitespace. try it and it will pass.
words = string.lower().split()
Steven Olick
1,561 PointsSteven Olick
1,561 PointsHi Mark, your answer helped me wrap my head around this a little better. My answer was not too far off from yours. However, I was wondering if you could explain this line for me. It was where I got stuck in my answer.
dict[word] = words.count(word)
What exactly does the dict[word] do?