Write a Python Program to check if a given key exists in a Dictionary with a practical example.
Python Program to check if a given key exists in a Dictionary Example 1
In this python program, we are using if statement and keys function to check whether the key exists in this Dictionary or not. If true, it prints the Key Value.
# Python Program to check if a Given key exists in a Dictionary myDict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange', 'm': 'Mango'} print("Dictionary : ", myDict) key = input("Please enter the Key you want to search for: ") # Check Whether the Given key exists in a Dictionary or Not if key in myDict.keys(): print("\nKey Exists in this Dictionary") print("Key = ", key, " and Value = ", myDict[key]) else: print("\nKey Does not Exists in this Dictionary")

Python Program to verify Given key exists in a Dictionary Example 2
This Python program is another approach to check the given key is present in a dictionary or not.
myDict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange', 'm': 'Mango'} print("Dictionary : ", myDict) key = input("Please enter the Key you want to search for: ") # Check Whether the Given key exists in a Dictionary or Not if key in myDict: print("\nKey Exists in this Dictionary") print("Key = ", key, " and Value = ", myDict[key]) else: print("\nKey Does not Exists in this Dictionary")
Dictionary : {'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'm': 'Mango'}
Please enter the Key you want to search for: m
Key Exists in this Dictionary
Key = m and Value = Mango
>>>
Dictionary : {'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'm': 'Mango'}
Please enter the Key you want to search for: g
Key Does not Exists in this Dictionary
>>>
Python Program to check if a key exists in a Dictionary Example 3
In this python program, we are using the get function to check whether the key exists or not.
myDict = {'a': 'apple', 'b': 'Banana' , 'o': 'Orange', 'm': 'Mango'} print("Dictionary : ", myDict) key = input("Please enter the Key you want to search for: ") # Check Whether the Given key exists in a Dictionary or Not if myDict.get(key) != None: print("\nKey Exists in this Dictionary") print("Key = ", key, " and Value = ", myDict[key]) else: print("\nKey Does not Exists in this Dictionary")
Dictionary : {'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'm': 'Mango'}
Please enter the Key you want to search for: a
Key Exists in this Dictionary
Key = a and Value = apple
>>>
Dictionary : {'a': 'apple', 'b': 'Banana', 'o': 'Orange', 'm': 'Mango'}
Please enter the Key you want to search for: x
Key Does not Exists in this Dictionary
>>>