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

Michael Wotherspoon
Michael Wotherspoon
1,564 Points

How do I directly compare items in a list to the keys in a dictionary to see if they match?

  • I believe the error is in line 12 but I may be wrong.
  • I also believe I am trying to increase the int. associated with the key incorrectly
  • Currently all words just seem to fall into the else statement
# 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(thing):
    # split thing into listed parts
    words1 = thing.lower()
    words = words1.split(' ')
    count = {}
    for word in words:
        if word == count.keys():
            count.update({word: +1})
        # if key is in count then update +1}
            count.update({word: 1})

    # for each part start with count,
    # compare part with all other parts,
    # if same increase count for each word
    # for word in thing.lower():
    # return dict({})

1 Answer

Cheo R
Cheo R
37,150 Points

The key here is this line:

if word == count.keys():

Instead of doing a comparison (your key to a list of keys), what you want to be doing is checking if the key is in the list of keys.