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 dictionaryIf 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
- A dictionary
myDictionaryis created with three key-value pairs:"name": "Lini","year": 1989, and"expertise": "data analytics". - The expression
'expertise' in myDictionarychecks whether the key'expertise'is present in the dictionary. - The result of this expression is stored in the variable
isPresent, which will beTrueif the key exists, orFalseif it does not. - The
print()function displays the result, which in this case will beTruesince the key'expertise'is present in the dictionary.
Output
TrueThe 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
- A dictionary
myDictionaryis created with three key-value pairs:"name": "Lini","year": 1989, and"expertise": "data analytics". - The expression
'place' in myDictionarychecks whether the key'place'is present in the dictionary. - The result of this expression is stored in the variable
isPresent, which will beFalsesince the key'place'is not found in the dictionary. - The
print()function displays the result, which in this case will beFalse.
Output
FalseThe 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.