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

Warren Chisasa
Warren Chisasa
3,731 Points

Adding keys to dictionaries

I am trying to add a key and and the number of times it appears in a string. But the issue is, I am getting a 'bummer!' and the warning is that 'some words are missing'. I am sure the problem is with the for loop but I couldn't find a way wrapping my head around the problem. Asking 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 (my_str):  # function to return string as key and value
    word_dict = {}
    my_str.lower()
    my_str.split()
    count = 1
    for word in my_str:   #iterate to add key and number of times it appears to dictionary 
        word_dict[word] = count
        count +=1
    return word_dict  

1 Answer

wang yang
PLUS
wang yang
Courses Plus Student 1,728 Points
def word_count(sentence):
    my_dict = {}
    sentence_lower = sentence.lower()
    for word in sentence_lower.split():
        value = sentence_lower.count(word)
        my_dict[word] = value
    return my_dict

didn't work too! says "Didn't get the right count for some of the words."

wang yang
wang yang
Courses Plus Student 1,728 Points
def word_count(sentence):
    my_dict = {}
    my_list = list(sentence.lower().split())
    for word in my_list:
        value = my_list.count(word)
        my_dict[word] = value
    return my_dict

this worked! but i don't know why i must put word in list

Warren Chisasa
Warren Chisasa
3,731 Points

Thanks! the second code worked!