How to check if a key exists in a python dictionary?

It's a common requirement to check for the existence of a key in a dictionary before performing some action.

Example:


  my_dict = {'a': 1, 'b': 2}
  key_exists = 'a' in my_dict
  

Solution:

Using the in keyword is the most Pythonic way to check for a key in a dictionary. It will return True if the key exists and False otherwise.

Beginner's Guide to Python