Python Check if Key Exists in Dictionary Example

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)

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)

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.

Code copied to clipboard successfully 👍