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 trialRodrigue Loredon
1,338 PointsHelp with word_count.py
Can someone tell me with my code is not working? I always get back an empty dictionnary.
# 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.
aString = "I am that I am"
aDict = {}
def word_count(aString):
count = 1
aSplitString = aString.lower().split()
for word in aSplitString:
if word not in aDict:
aDict.update({word:count})
else:
aDict.update({word:count+1})
continue
return aDict
4 Answers
Rodrigue Loredon
1,338 PointsThank you for you help. I was able to solve my problem. I wrote the function this way:
def string_factory(dicts,string):
final_list = []
for item in dicts:
newString = string.format(name='name',food='food')
final_list.append(newString)
return final_list
Take care
Gina Scalpone
21,330 PointsYou need to call the function for the dictionary to be updated.
Rodrigue Loredon
1,338 PointsHello Gina, I tried to call the function at the end of the script but that didn't work for me.
Gina Scalpone
21,330 PointsDid you call it with the aString as an argument? The function needs an argument to work, so just calling word_count() won't work, you need to call word_count(aString).
Rodrigue Loredon
1,338 PointsThanks for your help and insight it was much appreciated!
Gina Scalpone
21,330 PointsGina Scalpone
21,330 PointsI was able to run your code, so I'm not sure what the problem was, but I also rewrote it using a more common method: