Signup/Sign In

Python program to Handling missing keys in Python dictionaries

In this tutorial, you will learn to write a Python program that will handle missing keys in a dictionary in Python. Dictionaries in Python hold data in form of key-value pairs in which each value has its own unique key.

It may happen that a user does not know that a particular key is present or not in a dictionary and tries to access it.

In this case, the user will get an exception or a runtime error, so we have to write a program that will handle missing keys without giving any exceptions.

Let us see the input-output values for the program.

Input:

dict={'x': 23, 'y': 60, 'z': 12}

key= a

Output: Not found

Input:

dict={1: 'apple', 2: 'banana', 3: 'cherry'}

key= 1

Output: apple

To solve this problem, we can follow these approaches:

  1. using get() method
  2. using setdefault() method
  3. using defaultdict

Approach 1: using get() Method

In this approach, we will use the get() method. We will pass the key in this method along with a default value. If the key is found in the dictionary then this method will return the value of that key, else it will return the default value.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Define a dictionary with values

Step 2- Use get() and pass the key whose value has to be printed and a default value

Step 3- If the key is present the value of that key will be printed

Step 4- Else the default value will be printed

Python Program 1

Look at the program to understand the implementation of the above-mentioned approach. We have defined a dictionary with country codes as keys and their full forms as values.

dic= {'IND': 'India', 'USA': 'United States of America', 'AUS': 'Australia' }

# key is present
print(dic.get('USA','Not Found'))

#key is not present
print(dic.get('PAK','Not found'))


United States of America
Not found

Approach 2: using setdefault() method

The setdefault() method works in a similar way as the get() method and returns the value of the key if it is present in the dictionary. If the key is absent then this method will create a new key with the default value passed as an argument in the method as its value.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Define a dictionary with values

Step 2- Use setdefault() and pass the key whose value has to be checked and a default value

Step 3- If the key is present the value of that key will be printed

Step 4- Else the method will create a new key with the default value as its value

Python Program 2

Look at the program to understand the implementation of the above-mentioned approach.

dic= {'IND': 'India', 'USA': 'United States of America', 'AUS': 'Australia' }

# default val
dic.setdefault('JAP', 'Not Found')

# key is present
print(dic['IND'])

#key is not present
print(dic['JAP'])


India
Not Found

Approach 3: using defaultdict

The defautdict is a sub-class of dictionary class that returns an object without raising any errors if the key is not found. A normal dictionary will always give an error if the key is not present in the dictionary. It takes a function as an argument.

Algorithm

Follow the algorithm to understand the approach better.

Step 1- Import collections

Step 2- Declare the defaultdict

Step 3- Initialise keys and values

Step 4- Print the values using keys

Python Program 3

Look at the program to understand the implementation of the above-mentioned approach. To use defaultdict we have to import collections in our program. We have defined a lambda function in the defaultdict as an argument.

import collections

# declaring defaultdict
dic = collections.defaultdict(lambda: 'Key Not found')

# initialise keys and values
dic['IND']='India'
dic['USA']='United States of America'

# key is present
print(dic['IND'])

#key is not present
print(dic['JAP'])


India
Key Not found

Conclusion

In this tutorial, we have seen three different approaches for handling the exception of the missing key in a Python dictionary. We have seen how to use the get() method, the setdefault() method, and the defaultdict subclass of Python.