How to Check if Key Exists in Dictionary in Python?


Check if the Key is present in Python Dictionary

To check if a key is present in a Python Dictionary, you can use in keyword and find out.

In this tutorial, we will learn the syntax used to find out the presence of key in a dictionary, and some working examples.


Syntax to check if a key is in dictionary

Following is the syntax to check if key is present in dictionary. The expression returns a boolean value.

isPresent = key in dictionary

If the key is present in the dictionary, the expression returns boolean value True, else it returns False.


Examples

1. Check if a the key "expertise" is present in the dictionary

Consider a Python Dictionary named myDictionary and we shall check if a key is present or not.

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

isPresent = 'expertise' in myDictionary
print(isPresent)

Explanation

  1. A dictionary myDictionary is created with three key-value pairs: "name": "Lini", "year": 1989, and "expertise": "data analytics".
  2. The expression 'expertise' in myDictionary checks whether the key 'expertise' is present in the dictionary.
  3. The result of this expression is stored in the variable isPresent, which will be True if the key exists, or False if it does not.
  4. The print() function displays the result, which in this case will be True since the key 'expertise' is present in the dictionary.

Output

True

The key expertise is present in myDicitonary, and therefore we got True returned by in statement.


2. Check if key is present in the dictionary - Negative Scenario

In this example, we will try out a negative scenario where key is not present in the Python Dictionary.

myDictionary = {
	"name": "Lini",
	"year": 1989,
	"expertise": "data analytics"}

isPresent = 'place' in myDictionary
print(isPresent)

Explanation

  1. A dictionary myDictionary is created with three key-value pairs: "name": "Lini", "year": 1989, and "expertise": "data analytics".
  2. The expression 'place' in myDictionary checks whether the key 'place' is present in the dictionary.
  3. The result of this expression is stored in the variable isPresent, which will be False since the key 'place' is not found in the dictionary.
  4. The print() function displays the result, which in this case will be False.

Output

False

The key place is not present in myDictionary.


Summary

In this tutorial of Python Examples, we learned how to check if a key is present or not in a Python Dictionary with the help of well detailed examples.


Python Libraries