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 trialSwan The Human
Full Stack JavaScript Techdegree Student 19,338 PointsTrying to make a function that returns a dictionary with the amount of times each word in a string is used.
im not sure exactly how to begin this or if im on the right track with what i have so far. if anyone can help me slightly with where to start or what i have right and wrong i would appreciate it
# 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('this challenge is difficult'):
dict = {'this': 1, 'challenge': 1, 'is': 1, 'difficult': 1}
return(**dict.lower)
1 Answer
mhjp
20,372 PointsYou will need to iterate through the string, lowercasing and splitting on whitespace. Then add each item to the dict, first checking if it is already a dict key and incrementing the value if it is.
i.e.
def word_count(s):
word_dict = {}
for i in s.lower().split():
if i in word_dict:
#do something
else:
#do something else
return word_dict