Open In App

Check if a Key Exists in a Python Dictionary

Last Updated : 05 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python dictionary can not contain duplicate keys, so it is very crucial to check if a key is already present in the dictionary. If you accidentally assign a duplicate key value, the new value will overwrite the old one.

To check if given Key exists in dictionary, you can use either in operator or get() method. Both are easy are use and work efficiently.

Using IN operator

Python
# Example dictionary
d = {'a': 1, 'b': 2, 'c': 3}

# Key to check
key = 'b'
print(key in d)  # Output: True

key = 'g'
print(key in d)  # Output: False

Output
True
False

So in a given dictionary, our task is to check if the given key already exists in a dictionary or not.

Different Methods to Check If a Key Exists in a Dictionary

There can be different ways to check whether a given key Exists in a Dictionary, we have covered the following approaches:

Check If the Key Exists Using keys() Method

keys() method returns a list of all the available keys in the dictionary. With the Inbuilt method keys(), use the if statement with the ‘in’ operator to check if the key is present in the dictionary or not. 

Python
# Python3 Program to check whether a
# given key already exists in a dictionary.

def checkKey(dic, key):
    if key in dic.keys():
        print("Present, ", end =" ")
        print("value =", dic[key])
    else:
        print("Not present")
        
# Driver Code
dic = {'a': 100, 'b':200, 'c':300}
key = 'b'
checkKey(dic, key)

key = 'w'
checkKey(dic, key)

Output
Present,  value = 200
Not present

Check If the Key Exists Using get() Method

The Inbuilt method get() returns a list of available keys in the dictionary. With keys(), use the if statement to check whether the key is present in the dictionary. If the key is present it will print “Present” otherwise it will print “Not Present”.

Python
d = {'a': 100, 'b':200, 'c':300}

# check if "b" is none or not.
if d.get('b') == None:
  print("Not Present")
else:
  print("Present")

Output
Present

Handling ‘KeyError’ Exception while accessing dictionary

Use try and except to handle the KeyError exception to determine if a key is present in a diet. The KeyError exception is generated if the key you’re attempting to access is not in the dictionary.

Python
d = {'Aman': 110, 'Rajesh': 440, 'Suraj': 990}

try:
    d["Kamal"]
    print('Found')
except KeyError as error:
    print("Not Found")




Next Article

Similar Reads