Check if a Key Exists in a Python Dictionary
Last Updated : 05 Dec, 2024
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
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)
OutputPresent, 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")
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")
Similar Reads
Check If a Nested Key Exists in a Dictionary in Python Dictionaries are a versatile and commonly used data structure in Python, allowing developers to store and retrieve data using key-value pairs. Often, dictionaries may have nested structures, where a key points to another dictionary or a list, creating a hierarchical relationship. In such cases, it b
3 min read
Check if Tuple Exists as Dictionary Key - Python The task is to check if a tuple exists as a key in a dictionary. In Python, dictionaries use hash tables which provide an efficient way to check for the presence of a key. The goal is to verify if a given tuple is present as a key in the dictionary.For example, given a dictionary d = {(3, 4): 'gfg',
3 min read
Check if Value Exists in Python Dictionary We are given a dictionary and our task is to check whether a specific value exists in it or not. For example, if we have d = {'a': 1, 'b': 2, 'c': 3} and we want to check if the value 2 exists, the output should be True. Let's explore different ways to perform this check in Python.Naive ApproachThis
2 min read
Check and Update Existing Key in Python Dictionary The task of checking and updating an existing key in a Python dictionary involves verifying whether a key exists in the dictionary and then modifying its value if it does. If the key is found, its value can be updated to a new value, if the key is not found, an alternative action can be taken, such
4 min read
Check if dictionary is empty in Python Sometimes, we need to check if a particular dictionary is empty or not. Python# initializing empty dictionary d = {} print(bool(d)) print(not bool(d)) d = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(bool(d)) print(not bool(d)) OutputFalse True True False Different Methods to Check if a Dictionary is Em
5 min read