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 trialJohn Leonard
1,398 PointsMy code works when I run it in PyCharm but I get an error 'Didn't get the right count for some words'.
'''def word_count(string): string2 = string.lower() dict = {} list = string2.split() for element in list: dict.update({element : string2.count(element)}) return dict
# 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(string):
string2 = string.lower()
dict = {}
list = string2.split()
for element in list:
dict.update({element : string2.count(element)})
return dict
3 Answers
Chris Freeman
Treehouse Moderator 68,441 PointsYour code is close. You are counting on string2
which is not divided into words and may give false matches. Change string2
to list
:
def word_count(string):
string2 = string.lower()
dict = {}
list = string2.split()
for element in list:
dict.update({element : list.count(element)})
return dict
John Leonard
1,398 PointsHi Chris, thanks for the prompt feedback. Maybe I am missing something but I thought that list = string2.split() would split string2 into words? This list of words would be in 'list' then the count method is on the list (list.count(element). Please can you let me know where I am going wrong. Thank you.
Chris Freeman
Treehouse Moderator 68,441 PointsI thought that
list = string2.split()
would split string2 into words?
Correct.
This list of words would be in 'list' then the count method is on the list (list.count(element)).
Also correct.
Please can you let me know where I am going wrong. Thank you.
The difference is in your original code you had:
string2.count(element)
Instead of
list.count(element)
John Leonard
1,398 PointsAh, yes. I see that now! These forums are brilliant for people learning. It's often the little things that lead to hang-ups. Thanks a lot.
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsAdditional feedback: It is best not to use the names of built-in functions (
list
,dict
) as variable names. It worked in this code, but can have bad consequences in more complicated code.