Google News
logo
Python Program to Check if a key exists
In the following example of Python program to check if a key exists in a dictionary :
Program :
my_dict = {"name": "John", "age": 25, "gender": "Male"}

# check if key "name" exists in the dictionary
if "name" in my_dict:
    print("Key 'name' exists in the dictionary")
else:
    print("Key 'name' does not exist in the dictionary")

# check if key "address" exists in the dictionary
if "address" in my_dict:
    print("Key 'address' exists in the dictionary")
else:
    print("Key 'address' does not exist in the dictionary")
Output :
Key 'name' exists in the dictionary
Key 'address' does not exist in the dictionary