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 trialdinomueller
8,996 PointsPython dictionaries - word count challenge - clean solution?
Hi,
while I solved the challenge, I feel that my solution is clumsy and there might be a better way to do it? Also I used the get() method to check for non existing keys, which was not discussed in the course up to that point. So I think there might be a simpler and cleaner why to do it.
Does anbody have a better solution?
Thanks, Dennis
# 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(aString):
dictionary = {}
aString = aString.lower()
for word in aString.split():
if dictionary.get(word) == None:
dictionary.update({word: 1})
else:
dictionary.update({word: dictionary[word]+1})
return dictionary
1 Answer
Steven Parker
231,269 PointsYou might want to take a look at some of the other questions asked about this challenge (this link is from the "breadcrumbs" at the top of the question). Just remember that many, perhaps most, of the code will have errors and that's why it was posted. But it will allow you to see the variety of approaches taken to solve this task.