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 (2016, retired 2019) Dictionaries Word Count

Ian Cole
Ian Cole
454 Points

So Close! Help with dictionary keys

So I've got the program to assign each word to a key, and if it's a duplicate word it just assigns to the same value. But I can't get the duplicate key to increase the value. Every method I've tried so far has just given a KeyError

wordcount.py
# 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):
    lower_string = string.lower()
    split_string = lower_string.split(" ")
    word_dict = {}
    for word in split_string:
        word_dict[word] = 1
    return word_dict

1 Answer

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,887 Points

Hi Ian,

The problem I think you've been running into when incrementing the word in the dictionary is the first time you try to do it, there is no key with that name. Your code above executes because you can assign an initial value to a new dictionary key (of course):

my_dict['new_key'] = 1

But you can't initialise that key by incrementing:

my_dict['another_new_key'] += 1

since you can't add one to something that doesn't exist.

They way that I solved it was in the for loop to first check whether the word was a member of the keys list (word_dict.keys()), then if it was, to increment that value (since I've obviously already set that dictionary item to a value). If not, to initialise that key with the value 1 (i.e., the line you have in your code example).

Hope that helps,

Cheers

Alex