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 trialAndrei Oprescu
9,547 PointsCan someone help? I don't remember being thought this in any lesson.
Hi!
I have been given this challenge question that is asking me this:
Alright, this one might be a bit challenging but you've been doing great so far, so I'm sure you can manage it.
I need you to make a function named word_count. It should accept a single argument which will be a string. The function needs to return a dictionary. The keys in the dictionary will be each of the words in the string, lower cased. The values will be how many times that particular word appears in the string.
When I tried to approach this question, I have done it well, but when my result has to show how many of a certain word there were, I did not know how to do it.
My code that I am using is at the bottom of this page.
Can someone give me some advice on how to do this question?
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(sentence):
dictionary = {}
lower_sentence = lower(sentence)
listed_sentence = list(sentence)
for word in listed_sentence:
listed_sentence[word] = 1
return listed_sentence
2 Answers
Nicholas Ward
5,797 PointsOn the right track! A couple quick things:
- lower() is a string method, meaning you want to use it like this: "StRiNg".lower() will return "string" https://www.tutorialspoint.com/python/string_lower.htm
- list(string) returns a list of each individual letter in the string. A more useful method in this case is string.split(), which returns a list that breaks the string up by whitespace (in between each word) by default. https://www.tutorialspoint.com/python/string_split.htm
- To get from listed_sentence to the dictionary you want to use logic that looks something like this (in pseudocode):
for word in listed_sentence:
If the word is already in the dictionary:
increment the value by one
If the word is not in the dictionary yet:
add the word into the dictionary with a value of 1
Andrei Oprescu
9,547 PointsOh, thanks!
This worked and I will definitely use some of the logic used in this challenge.
Thank you for your support!