How to Check if Key Exists in a Python Dictionary

This tutorial covers the different ways of checking if a key exists in a dictionary in Python.

 

Using the in Operator to Check if Key Exists in Dictionary Python

The easiest and most commonly used way of finding out if a dictionary contains a particular key is to use the in operator in an if statement like this:

 

items = {'a': 1, 'b':2, 'c':3}

if "b" in items:
   print("Exists")
else:
   print("Does not exist")
Exists

 

In the above example, the key 'b' exists so the code inside the if statement block runs.

 

Check If Key Does NOT Exist in a Python Dictionary

To reverse the logic of the above example and check if a key doesn't exists in a dictionary, use the Python not operator like this:

 

items = {'a': 1, 'b':2, 'c':3}

if "d" not in items:
   print("Doesn't exist")
Doesn't exist

 

'd' is not in the dictionary so the code in the if block runs.

 

 

Check for Dict Key Using the Python get() Method

The Python get() method returns the value of the key you specify as the first argument. If there is not key it returns None.

 

items = {'a': 1, 'b':2, 'c':3}

if items.get('a') is not None:
   print('Exists')
Exists

 

The obvious problem with the above solution is if the key exists but its value is None. If you're sure you will never encounter a None value in the dictionary then this method works fine.