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 trialPrisca Egbua
1,167 PointsThe function word_count takes a string and returns a dictionary.
Each word is the key and the number of occurrences is the value. It keeps giving me an error, can someone please explain what I need to do. THANKS
# 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(single_string):
single_string = single_string.lower()
print(single_string)
single_list = single_string.split()
print(single_list)
some_dict = {}
for select_word in single_list:
count = 0
select_word=some_dict.keys
for word in some_dict:
if word==select_word:
count +=1
count=some_dict.values
print(some_dict.items)
1 Answer
Grigorij Schleifer
10,365 PointsHi Prisca,
I like the logic behind your approach! I modified your code and added a couple comments. You dont need to print anything for this challenge so I removed all print statements.
What I did:
# all print statements removed
def word_count(single_string):
# you can chain lower() and split()
# it is easier to read and less code to write
# plus you create less variables in memory (more efficient code)
single_list = single_string.lower().split()
some_dict = {}
for select_word in single_list:
count = 0
for word in single_list: # loop over single_list not your dictionary
if word==select_word:
count +=1
some_dict[select_word] = count
return some_dict # you print the dictionary instead of returning it
The way you tried to add keys and values to the dictionary will not work. You should use this pattern:
# you can add value to the key like this
dictionary[key] = value
If you want to get values from the dictionary you use the values() method WITH parenthesis (hint). If you want the keys you use keys() ...
Does it make sense?
Grigorij Schleifer
10,365 PointsAnother neat way to add key:value pairs is to use the update() method.
some_dict.update({select_word:count})
The update method expects a dictionary with the key:value pair ... pretty cool right ...
Prisca Egbua
1,167 PointsThanks for the detailed explanation. It work
Grigorij Schleifer
10,365 PointsGrigorij Schleifer
10,365 PointsNice! See you in the forum, Prisca!