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 trialKars Jansens
5,348 Pointswordcount problem [python]
question: 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, lowercased. The values will be how many times that particular word appears in the string.
Check the comments below for an example.
I have no idee how to fix this.
# 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):
string.lower()
for word in string:
count = count + 1
dit = {word:count}
return dit
5 Answers
Timotheus Taruvinga
2,319 PointsHie Kars I think you don't need no counting in a dictionary setup. you'll get your numbers in a haphazard way as they are in your >code. Check out for this pretty smart code. It does all you want.
def word_count(str): counts = dict() tim= str.lower() words = tim.split() for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 return counts print( word_count('the quick brown Fox jumps over the lazy dog.'))
Kars Jansens
5,348 Pointsdef word_count(sting): string = sting.lower() stringa = string.split() dit = {} for word in stringa: count = 1 for key in dit.keys(): if word == key: count = count + 1 dit.update({word:count}) else: dit.update({word:count}) return dit print(word_count("hoi ik ben kars"))
My output is '{}'.
Kars Jansens
5,348 Pointsthe output is {}. once I head a dictionary returned with al the words but the count didn't work.
def word_count(string):
strings = string.lower
for word in string:
if word is not in dic.keys():
count = 1
dic = {word: count}
else:
count = count + 1
dic = {word: count}
Kars Jansens
5,348 Pointsdef word_count(sting):
string = sting.lower()
stringa = string.split()
dit = {}
count = 0
for word in stringa:
count = count + 1
dit.update({word:count})
return dit
print(word_count("hello ik ben ik kars"))
Can you just tell me how I need to do this? I really don't know.
Kars Jansens
5,348 PointsYou're right that is pretty smart code..