Start learning free

LESSON 127 OF 673 · DICTIONARIES

Checking for a Key in Python

Lesson

TL ; DR:

Write key in d to ask whether a dictionary has a key. The answer is True or False, so it goes in an if.


capitals = {"France": "Paris", "Japan": "Tokyo"}

if "Japan" in capitals:
    print(capitals["Japan"])    # Tokyo

if "Spain" not in capitals:
    print("No Spain")           # No Spain


Full lesson:

Reading a key that isn't there is an error. capitals["Spain"] stops the program with a KeyError.

So check first. "Spain" in capitals is True when "Spain" is a key. It is False when it isn't.

not in asks the opposite. "Spain" not in capitals is True here, so No Spain prints.

A value is not a key

in looks only at the keys. "Paris" in capitals is False, because "Paris" is a value.

To look in the values, write "Paris" in capitals.values().

A key must match exactly, upper and lower case too. "japan" in capitals is False.


Your task

In pets, each key is a pet's name, and its value is the pet's kind.

First, check whether "Tom" is a key of pets. If it is, print Tom is a followed by Tom's kind.

Then check that "cat" is not a key, with not in. If so, print cat is not a key.

"cat" is in pets, but only as a value. It is Tom's kind.

Expected output:

Tom is a cat
cat is not a key
STEP 1 OF 2
    Ctrl + Enter to check