How to check if a key or value exists in a Python dictionary

A Python dictionary is a set of pairs like that.

d = {'book': 5, 'pen': 9}

It means there are 5 books and 9 pens. In this case, book is a key and 5 is its value. pen is a key and 9 is its value. We can check the existence of keys.

d = {'book': 5, 'pen': 9}

if 'book' in d:
    print('Exist!')
else:
    print('None')

# Exist!

Because the dictionary has book key, Exist! is printed. You can easily check whether a dictionary has a certain key or not by using the if-in statement.

d = {'book': 5, 'pen': 9}

if 'car' in d:
    print('Exist!')
else:
    print('None')

# None

This dictionary doesn't have car key so None is printed in the above example. A dictionary can contain any objects including dictionaries. That kind of dictionary is called "Nested dictionary". For-in statement checks only "top-level" keys in a nested dictionary.

d = {
    'book': {'price': 25, 'page': 60, },
    'pen': {'sale': 129},
}

print(type(d))  # <class 'dict'>

if 'book' in d:
    print("d has book.")
else:
    print("d doesn't have book.")

# d has book.

if 'sale' in d:
    print("d has sale.")
else:
    print("d doesn't have sale.")

# d doesn't have sale.

sale is a key of pen dictionary but is not directly a key of d.

Check if a key exists in a dictionary using keys()

The if-in statement is the simplest and most common way to check the key exsitence but there is another way using the dictionary method keys() as follows.

d = {'book': 5, 'pen': 9}

if 'pen' in d.keys():
    print('d has pen.')
else:
    print('d does not have pen.')

# d has pen.

This function returns a dict_keys object containing all the dictionary keys like a list.

d = {'book': 5, 'pen': 9}

print(d.keys())  # dict_keys(['book', 'pen'])
print(type(d.keys()))  # <class 'dict_keys'>

Check if value exists in dictionary

You can check if a value exists in the dictionary as follows.

d = {'CA': 'California', 'NV': 'Nevada', 'TX': 'Texas'}

if 'California' in d.values():
    print('California is in d.')

# California is in d.

values() method returns the dictionary values as an iterable.

Python Dictionary

Python Tutorial