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 trialKalinga Ranasinghe
6,484 PointsPython dictionary - Word Count: what's wrong with my code?
I get the correct result, but challenge code validator stats it's not.
# 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):
list_string = string.split()
dictionary = {}
for word in list_string:
word_count = string.count(word)
dictionary[word.lower()] = word_count
return dictionary
2 Answers
Alex Koumparos
Python Development Techdegree Student 36,887 PointsHi Kalinga,
You're getting the correct result for the example string, but you get the wrong result for other strings.
Look at the result you get for, e.g., "hello Hello HELLO hElLo Hello HELLO" and compare it to what you'd expect.
Cheers
Alex
Kalinga Ranasinghe
6,484 PointsHi Alex,
Thank you for taking the time for this.
def word_count(single):
words = single.lower().split()
dictionary = {}
for word in words:
dictionary[word] = words.count(word)
return dictionary
This fixed my issue.