Contents
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 – Key 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.
Example 1: Check if Key is present in Python 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)
Run Output
True
The key expertise
is present in myDicitonary
, and therefore we got True
returned by in
statement.
Example 2: Check if Key is present in Python 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)
Run 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.