How to Check If Key Exists in Dictionary in Python
To check if a key exists in a dictionary in Python, you can use the in operator or the get() function.
The following examples show how to check if a key exists in a dictionary in Python.
Using in Operator
We can use the in operator to check if a key exists in a dictionary.
Suppose we have the following dictionary:
# Declare dictionary
dict1 = {"A": 12, "B": 13, "C": 15}
# Check if key exists or not
if 'A' in dict1:
print("The key exists in the dictionary.")
else:
print("The key does not exist in the dictionary.")
Output: 👇️
The key exists in the dictionary.
In this example, we use the in operator to check if the key ‘A’ exists in the dictionary dict1.
Using get() Function
We can use the get() function to check if a key exists in a dictionary.
Suppose we have the following dictionary:
# Declare dictionary
dict1 = {"A": 12, "B": 13, "C": 15}
# Check if key exists or not
if dict1.get('A') is not None:
print("The key exists in the dictionary.")
else:
print("The key does not exist in the dictionary.")
Output: 👇️
The key exists in the dictionary.
In this example, we use the get() function to check if the key ‘A’ exists in the dictionary dict1. If the key is found, the function returns its value; otherwise, it returns None.
Conclusion
We can use the in operator and the get() function to check if a key exists in a dictionary in Python.