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 trialHiren Mistry
1,138 PointsI am consistently getting the correct output however the challenge is not accepting my answer, please check my code.
def word_count(sentence):
my_dict = dict()
my_list = sentence.split(' ')
for i in my_list:
my_dict.update({i:sentence.count(i)})
return(my_dict)
Questions: 1) Why is my answer not accepted? 2) Why are we adding 1 every time there is more than 1 appearance of a word instead of just counting all the appearances at once? 3) When I wrote " my_dict.update({i:sentence.count(i)}) " I expected to see each single word to be laid out. e.g. word_count("I am that I am") Expected: {'I':2, 'am':2, 'that':1, 'I':2, 'am':2} Observed: {'I':2, 'am':2, 'that':1}
Side Question: I am looking at the Markdown Cheatsheet, but I cannot seem to figure out why my posts are appearing as one long paragraph and ignoring everytime I make a new line
4 Answers
Joshua Edwards
52,175 Pointsif you have a sentence "bob went to see bob" your dictionary would be ->
bob:2 went:1 to: 1 see: 1 bob: 2
you need to check if bob is already in the dictionary to not create a duplicate key
Kenneth Love
Treehouse Guest TeacherYou can't actually create duplicate keys in a dict. Keys are always unique.
You also need to lowercase your string like it suggests in the comments.
Joshua Edwards
52,175 PointsThe way your code is working it is assigning a key to every word then returning how many times it appears. But since it is going through the whole string it is duplicating keys since you aren't checking if the key is already in the dictionary.
They give you a hint in the comments as to how to do that.
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).
Hiren Mistry
1,138 PointsI am not seeing any duplication in my output, why would I need to do this?