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

Christopher Wommack
Christopher Wommack
3,983 Points

word_count.py

help don't know what I am doing wrong says some words are missing

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(s):
    s = s.lower()
    dictionary = {}
    count = 0
    list_s = s.split()
    for word in list_s:
        if word in dictionary:
            count = dictionary[word]
            count += 1
            dictionary.update({word: count})
    return dictionary

1 Answer

Hi Christopher,

It looks like you're going to be returning an empty dictionary.

Initially, your dictionary is empty. Then you only have in if condition in your loop. This condition is never going to be true since the dictionary doesn't have any words in it.

Your if block takes care of what the 2nd to last code comment is saying. The last code comment gives you a suggestion on what to do if the word wasn't in the dictionary. You can put that in an else statement.

Also, there's an easier way to increment the count in your if block.

dictionary[word] += 1

This will take the current count, add 1 to it, and then store it back as the count for that word.