How to check if a key exists in a Python dictionary
Assume you have a Python dictionary like so:
where the keys are strings corresponding to seasons and the values are numbers. If we attempt to do:
we will get:
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:
The output will be:
If we change the key to Autumn:
we will get:
By default “in” checks for the existence of keys not values. So if you do:
you will get:
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:
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:
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’:
The output of the above will be:
If we tried:
we will obtain:
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?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.