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 trial

Python Python Collections (Retired) Dictionaries Word Count

Pincemail Sebastien
PLUS
Pincemail Sebastien
Courses Plus Student 2,411 Points

whats wrong with my function

Hello guys ,

i can't get out of this task , could you help to understand how can i count and update properly this dict. Thank you for help

word_count.py
# 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(sentence):
    word_dict = dict()
    count_dict = dict()
    count = 0
    sentence_list = sentence.split()
    for word in sentence_list:
        word_dict[word] = count
        if word in word_dict:
            word_dict[word] = count + 1
            count_dict.update(word_dict)
    return word_dict

1 Answer

I don't want to give you the answer in a cut and pastable form directly but I will instead ask a couple questions

(1) count_dict - you don't test this anywhere and you don't return it

(2) you are missing something from line 3 of the comments

(3) for each word you find in the sentence you always set the count of that word to 0 So if you have a sentence like "a a a a a a" you set the count 6 times to zero, should only be one time check what you are meaning to do exactly in this line word_dict[word] = count