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 trialeodell
26,386 PointsWord_Count function. My code works but isn't accepted..
Hello. I am trying to pass the word_count challenge and in my personal python (v2.7) editor I am running:
def word_count(string):
dictionary = {}
words = string.lower().split(" ")
for word in words:
key = word
count = 0
for word in words:
if word == key:
count += 1
dictionary[key] = count
return dictionary
and getting the correct results. I return a dictionary with each key being the lowercase version of the words (found by splitting the argument on " ") and an accurate count of the frequency as an integer for the value of each key. Am I missing a step or is something wrong the code? Any insight would be appreciated.
# 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):
dictionary = {}
words = string.lower().split(" ")
for word in words:
key = word
count = 0
for word in words:
if word == key:
count += 1
dictionary[key] = count
return dictionary
2 Answers
Christopher Shaw
Python Web Development Techdegree Graduate 58,248 PointsThis is a common issue with this challange. Use split(), not split(' '). Your version will only split on single white spaces while split() splits on single or mutiple whitespaces.
eodell
26,386 PointsThank you for that explanation!