Example-1: Occurrence of KeyError exception for invalid key
Create a python file with the following script to check the occurrence of KeyError for the invalid key of the dictionary. In the script, a dictionary of three key-value pairs has been declared. Next, three keys have been used to read the dictionary values where the key named ‘type’ does not exist in the dictionary. The KeyError will occur at the time of reading the ‘type’ value.
dic_customers = {'customer_id': 'B-45322', 'name': 'Meena Kumari', 'account_type': 'Saving'}
# Read and print the customer ID
id = dic_customers['customer_id']
print("Customer ID: ", id)
# Read and print the customer name
name = dic_customers['name']
print("Customer Name: ", name)
# Read and print the account type
type = dic_customers['type']
print("Account Type: ", type)
Output:
The following output will appear after executing the above script. The values of the valid keys of the dictionary have been printed, and the KeyError has been displayed for the invalid key, ‘type’.
Example-2: Handling KeyError Exception using try-except block
The KeyError exception can be handled in different ways. One way is to use the try-except block to handle this error. Create a python file with the following script to handle the KeyError using try-except block. A dictionary of three elements has been declared in the script. The KeyError will occur at the time of reading the value of the key named ‘type’ that does not exist in the dictionary, and the custom error message will be displayed.
dic_customers = {'customer_id': 'B-45322', 'name': 'Meena Kumari', 'account_type': 'Saving'}
try:
# Read and print the customer ID
id = dic_customers['customer_id']
print("Customer ID: ", id)
# Read and print the customer name
name = dic_customers['name']
print("Customer Name: ", name)
# Read and print the account type
type = dic_customers['type']
print("Account Type: ", type)
except KeyError as key:
# Print error message
print('{} key does not exist in the dictionary.'.format(key))
Output:
The following output will appear after executing the above script. The values of the valid keys of the dictionary have been printed, and the error has been displayed for the invalid key.
Example-3: Avoiding KeyError Exception using get() function
The KeyError exception can be avoided by using the get() function without using the try_except block. The get() is a built-in function of python to read the value of the particular key of the dictionary. This function returns the value of the key if the key exists; otherwise, it returns None. Create a python file with the following script to know how to avoid the KeyError by using the get() function. In the script, the get() function has been used to read two valid keys and one invalid key of the dictionary.
dic_customers = {'customer_id': 'B-45322', 'name': 'Meena Kumari', 'account_type': 'Saving'}
# Set the key value
key = 'name'
# Print the value of the key if exists
print("The value of {} key is: {}".format(key, dic_customers.get(key)))
# Set the key value
key = 'type'
# Print the value of the key if exists
print("The value of {} key is: {}".format(key, dic_customers.get(key)))
# Set the key-value
key = 'balance'
'''
Print the value of the key if exists,
otherwise set the value for the new key
'''
print("The value of {} key is: {}".format(key, dic_customers.get(key, 60000)))
Output:
The following output will appear after executing the above script. The ‘type’ key does not exist in the dictionary. So, the ‘None’ value has been returned by the get() function for this key.
Example-4: Avoiding KeyError Exception using if-else statement
The KeyError exception can also be avoided without using the get() function. Create a python file with the following script to avoid the KeyError exception by checking the existence of the key of the dictionary. The function named ‘check_key’ has been declared in the script to check the existence of each key of the dictionary. The function will return the formatted value of the key if the key exists in the dictionary; otherwise, it will return the error message. A dictionary of three elements has been used here. At first, the ‘customer_id’ will be checked that exists in the dictionary. Next, the ‘type’ key that does not exist in the dictionary will be checked.
def check_key(k, dic):
if k in dic.keys():
print("The value {} key is {}.".format(k, dic[k]))
else:
print("{} key does not exist in the dictionary.".format(k))
# Declare a dictionary
dic_customers = {'customer_id': 'B-45322', 'name': 'Meena Kumari', 'account_type': 'Saving'}
# Call the function to check the 'customer_id' key
check_key('customer_id', dic_customers)
# Call the function to check the 'type' key
check_key('type', dic_customers)
Output:
The following output will appear after executing the above script. The value of the ‘customer_id’ key has been printed, and the error message has been printed for the ‘type’ key.
Conclusion:
Different ways to avoid the KeyError exception that occurs for the non-existing key of the python dictionary have been shown in this tutorial. The python users can follow any of the ways mentioned here based on their requirements.