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 trialUnsubscribed User
Full Stack JavaScript Techdegree Graduate 27,351 PointsUnable to complete python word-count challenge
Hello everyone.
I'm having difficulties with the python code challenge found here: https://teamtreehouse.com/library/python-collections-2/dictionaries/word-count
I hope somebody will be able to help me understand how to complete this challenge.
Below is the code I have written:
# 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):
lowered_string = string.lower()
word_list = lowered_string.split(" ")
dictionary = {}
for word in word_list:
dictionary.update({word: 0})
for word in word_list:
dictionary[word] = dictionary[word] + 1
return dictionary
2 Answers
Steven Parker
231,275 PointsYou're really close! And your error message contains a hint: "Bummer: Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!"
To split on "all whitespace" you should leave the argument to the "split" function empty. Giving it a space causes it to split on individual spaces exclusively. For more details, see the documentation on str.split().
Unsubscribed User
Full Stack JavaScript Techdegree Graduate 27,351 PointsWoops! Thanks Steven Parker, I guess I was thinking like JavaScript, not Python!
Silly me!
Thanks for your answer!
akoniti
1,410 PointsYour seems to work in a quick test with a small change:
word_list = lowered_string.split()
You'll notice I removed the quotation marks from your split method arguments.
Unsubscribed User
Full Stack JavaScript Techdegree Graduate 27,351 PointsYeah, that seems to have been the problem! Thanks akonti!
Steven Tagawa
Python Development Techdegree Graduate 14,438 PointsSteven Tagawa
Python Development Techdegree Graduate 14,438 PointsI copied your code into a Workspace and it seemed to work fine. (It returned a dictionary with the correct word counts for the example string.) Are you getting an error message, and if so, what is it?