
Check if a given key already exists in a dictionary in Python
Dictionary is an unordered collection of data in the form of key-value pairs separated by commas inside curly brackets. Dictionaries are indexed by keys. They are generally optimized to retrieve values when the key is known. Values (definitions) are mapped to a specific key (words) similar to that of a dictionary in the real world.
Now our task is to check if a given key exists in a dictionary or not. We can accomplish this through the ways below:
- Using the keys() method
- Using if and in
- Using has_key()
- Using keys() method:
This inbuilt method returns a list of all the available keys in a given dictionary. We use this along with the ‘in’ keyword.
Example:
def fun_check_key(dict, key):
if key in dict.keys():
print("The key is present in dictionary", end ="\n")
print("Corresponding value is:", dict[key])
else:
print("The key is present in the dictionary")
dict = {'One': '1', 'Two': '2', 'Three': 3}
key = 'Two'
fun check key(dict,key)
key = 'Four'
fun_check_key(dict, key)Output:

- Using if and in:
Here we won’t necessarily use the keys() method. It just returns a boolean value, True if present else returns False
Example:
def fun_check_key(dict, key):
if key in dict.keys():
print("The key is present in dictionary", end ="\n")
print("Corresponding value is:", dict[key])
else:
print("The key is present in the dictionary")
dict = {'One': '1', 'Two': '2', 'Three': 3}
key = 'Two'
fun check key(dict,key)
key = 'Four'
fun_check_key(dict, key)Output:

- Using has_key():
This method also returns a boolean value, True if the key is present in the dictionary else False. We use this method along with the if statement as shown below.
Example:
if dict.has_key(key):
Output:

This method is no longer supported by the versions Python 3 and above. We can only use it in Python 2. The output is much similar to the above mentioned ways.