Handling missing keys in Python dictionaries
In this lesson, you will discover how to create a Python application that will manage missing keys in a dictionary. Python dictionaries store data as key-value pairs, where each value has a distinct key.
A user may attempt to access a key that they are unaware is either existent or absent in a dictionary.
Since the user will encounter an exception or runtime error in this scenario, we must create a program that can deal with missing keys without raising any errors.
Let's look at the program's input-output values.
Input:
Dict_jtp={'x':1, 'y': 2, 'z': 3}
key= a
Output: Traceback (most recent call last):
File "<string>", line 2, in <module>
NameError: name 'a' is not defined
These methods can be used to address this issue:
- Using get() method in the python for dictionary.
- Using setdefault() method in the python for dictionary.
- Using defaultdict method in python.
Method 1: use the get() command:
In this strategy, we'll employ the get() method. In this method, the Key and a default value will be passed. This method will return the value of the Key if it can be found in the dictionary; else, it will return the default value.
Algorithm
For a better understanding of the strategy, follow the algorithm.
Step 1: Create a values-only dictionary
Step 2: Call get() and pass a default value along with the Key whose value has to be printed.
Step 3: The value of the Key will be printed if the Key is present.
Step 4: The default value will be displayed if not.
Python Program to explain the get() method.
To understand how the abovementioned strategy is implemented, look at the program. Cities' codes have been used as keys in a dictionary, and their real names have been used as values.
Input:
dict_jtp = { 'Hyd': 'Hyderabad', 'Dl' :' Delhi' , 'Mum' : 'Mumbai' , 'BGL' : 'Bengaluru' }
print( dict_jtp.get ( 'Hyd' , 'Not Found' ) )
print( dict_jtp.get ( 'Dl', 'Delhi') )
print( dict_jtp.get( 'Kol' , 'Not Found' ))
Output:
Hyderabad
Delhi
Not Found
Method 2:using the setdefault() method in python for the dictionary.
If the Key is found in the dictionary, the setdefault() method operates similarly to the get() method and returns the value of the Key. If the Key is missing, this method will generate a new key using the argument's default value as its value if the Key is not present.
Algorithm
For a better understanding of the strategy, follow the algorithm.
Step 1: Create a values-only dictionary
Step 2: Call setdefault() and provide a default value along with the Key whose value has to be checked.
Step 3: The value of the Key will be printed if the Key is present.
Step 4: If not, the method will create a new key and set its value to the default.
Input:
dict_jtp = { 'Hyd' : 'Hyderabad' , 'Dl' :' Delhi' , 'Mum' : 'Mumbai' , 'BGL' : 'Bengaluru' }
# default value in the python
dic.setdefault('WBL', 'Not Found')
# key is presented in the python
print(dic['Hyd'])
#key is not present in python.
print(dic['WBL'])
Output:
Hyderabad
Not Found.
Method 3:using defaultdict method in the python.
If the Key cannot be located, the default dict subclass of the dictionary class returns an object without reporting any issues. A typical dictionary will always provide an error if the Key is missing from the dictionary. A function is accepted as an argument.
Algorithm
For a better understanding of the strategy, follow the algorithm.
Step 1: import the collections.
Step 2:Declare the defaultdict.
Step 3: Initialize the values and keys.
Step 4: Use keys to print the values
To understand how the strategy mentioned above is implemented, look at the program. We need to import collections into our program before we can utilize defaultdict. A lambda function has been defined and is used as an argument in the defaultdict.
Input:
import collections
# declaring defaultdict in the python to handle the error with the dictionary.
Dict_jtp = collections.defaultdict(lambda: 'Key is not present')
# initialize keys and their values in the program.
Dict_jtp['Hyd’]='Hyderabad'
Dic_jt[['MUM']='Mumbai'
# key is present in the python program.
print(dict_jtp['HYD'])
#key is not presented in the python program.
print(dict_jtp['Ram'])
Output:
Hyderabad
The Key is not present.