The dictionary containers in pipeline old both key and values as pairs. Sometimes we may need to find if a given key is already present in the dictionary. In this article we will see the various ways to check for the presence of a key in a dictionary.
With in
This is a very straightforward way in which we just check for the presence of the key in the dictionary using in operator. If the the keys part of dictionary we print the result as present else absent.
Example
Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9} print("The given dictionary : ",Adict) check_key = "Fri" if check_key in Adict: print(check_key,"is Present.") else: print(check_key, " is not Present.")
Output
Running the above code gives us the following result −
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5} Fri is not Present.
With dict.keys
The dict.keys() method gives us all the keys that are present in a given dictionary. We can use the in operator how to find out if the given key belongs to the given dictionary.
Example
Adict = {'Mon':3,'Tue':5,'Wed':6,'Thu':9} print("The given dictionary : ",Adict) check_key = "Wed" if check_key in Adict.keys(): print(check_key,"is Present.") else: print(check_key, " is not Present.")
Output
Running the above code gives us the following result −
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5} Wed is Present.