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 trialSiva Krishna Raju Vegesina
1,877 PointsNeed help in word_count() challenge
Could someone help me what's wrong with my code.
# 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.
def word_count(str1):
str1_list = str1.lower().split()
str1_dict = {}
for word in str1_list:
count = 1
if word in str1_dict:
count += 1
str1_dict[word] = count
else:
count = 1
str1_dict[word] = count
return str1_dict
1 Answer
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi Siva
Cant see much wrong with your code apart from a bit of cleaning up so not sure why the challenge marker doesn't pass. My code seems to work see below.
def word_count(str1):
str1_list = str1.lower().split()
str1_dict = {}
for word in str1_list:
if word in str1_dict:
str1_dict[word] = str1_dict[word]+1
else:
str1_dict[word] = 1
return str1_dict
hope this helps