Kodeclik Blog
How to check if a key exists in a Python dictionary
Assume you have a Python dictionary like so:
seasons = {'Spring': 1,
'Summer': 2,
'Fall': 3,
'Winter': 4}
where the keys are strings corresponding to seasons and the values are numbers. If we attempt to do:
print(seasons['Summer'])
print(seasons['Autumn'])
we will get:
2
Traceback (most recent call last):
File "main.py", line 7, in <module>
print(seasons['Autumn'])
KeyError: 'Autumn'
The first print line succeeds because there is a key called ‘Summer’ which maps to value 2. The second print line fails because Python says there is a ‘KeyError’, i.e., there is no key called ‘Autumn’. Thus we need a way to check if a key is in a given Python dictionary to avoid errors like this. There are at least three ways to do. Lets learn about them!
Method 1: 1. Use if and in
Our first approach is simplicity itself. It simply checks if the given key is “in” the dictionary, like so:
seasons = {'Spring': 1,
'Summer': 2,
'Fall': 3,
'Winter': 4}
key = 'Summer'
if key in seasons:
print(seasons[key])
else:
print("Key not found")
The output will be:
2
If we change the key to Autumn:
seasons = {'Spring': 1,
'Summer': 2,
'Fall': 3,
'Winter': 4}
key = 'Autumn'
if key in seasons:
print(seasons[key])
else:
print("Key not found")
we will get:
Key not found
By default “in” checks for the existence of keys not values. So if you do:
seasons = {'Spring': 1,
'Summer': 2,
'Fall': 3,
'Winter': 4}
key = 2
if key in seasons:
print(seasons[key])
else:
print("Key not found")
you will get:
Key not found
because there is no key called 2.
Method 2: Use if and in with the keys() method
The second approach is very similar to the above with one small modification:
seasons = {'Spring': 1,
'Summer': 2,
'Fall': 3,
'Winter': 4}
key = 'Winter'
if key in seasons.keys():
print(seasons[key])
else:
print("Key not found")
In the “if” check we check if the key is in “seasons.keys()” instead of just “seasons”, even though the semantics of both are the same. seasons.keys() returns a list of all keys and we are checking if the given key is part of this list. The output of the above is:
4
as expected.
Method 3: Try accessing the value for the key using get() and see if you get ‘None’ or otherwise
In the final approach we will use the get() method which instead of complaining if the key does not exist returns ‘None’:
seasons = {'Spring': 1,
'Summer': 2,
'Fall': 3,
'Winter': 4}
key = ‘Fall’
if (seasons.get(key) != None):
print(seasons[key])
else:
print("Key not found")
The output of the above will be:
3
If we tried:
seasons = {'Spring': 1,
'Summer': 2,
'Fall': 3,
'Winter': 4}
key = 'Autumn'
if (seasons.get(key) != None):
print(seasons[key])
else:
print("Key not found")
we will obtain:
Key not found
Working with dictionaries in Python can be a bit counter-intuitive. Here we have seen three different ways to check if a key is part of a Python dictionary. This is important for understanding how the dictionary works and for debugging your code in case it doesn’t work (e.g., it might be trying to access a key that does not exist). Which of the three ways is your favorite?
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.