Handling missing keys in Python dictionaries

PythonProgrammingServer Side Programming

In Python there is one container called the Dictionary. In the dictionaries, we can map keys to its value. Using dictionary the values can be accessed in constant time. But when the given keys are not present, it may occur some errors.

In this section we will see how to handle these kind of errors. If we are trying to access missing keys, it may return errors like this.

Example code

Live Demo

country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}
print(country_dict['Australia'])
print(country_dict['Canada']) # This will return error

Output

AU
---------------------------------------------------------------------------
KeyErrorTraceback (most recent call last)
<ipython-input-2-a91092e7ee85> in <module>()
      2 
      3 print(country_dict['Australia'])
----> 4 print(country_dict['Canada'])# This will return error

KeyError: 'Canada'

Using get() Method to handle KeyError

We can use the get method to check for keys. This method takes two parameters. The first one is the key, and the second one is the default value. When the key is found, it will return the value associated with the key, but when the key is not present, it will return the default value, which is passed as second argument.

Example code

Live Demo

country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}
print(country_dict.get('Australia', 'Not Found'))
print(country_dict.get('Canada', 'Not Found'))

Output

AU
Not Found

Using setdefault() Method to handle KeyError

This setdefault() method is similar to the get() method. It also takes two argument like get(). The first one is the key and the second one is default value. The only difference of this method is, when there is a missing key, it will add new keys with default value.

Example code

Live Demo

country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}
country_dict.setdefault('Canada', 'Not Present') #Set a default value for Canada
print(country_dict['Australia'])
print(country_dict['Canada'])

Output

AU
Not Present

Using defaultdict

The defaultdict is a container. It is located at the collections module in Python. The defaultdict takes the default factory as its argument. Initially the default factory is set to 0 (integer). When a key is not present, it returns the value of default factory.

We do not need to specify the methods again and again, so it provides faster method for the dictionary objects.

Example code

Live Demo

import collections as col
#set the default factory with the string 'key not present'
country_dict = col.defaultdict(lambda: 'Key Not Present')
country_dict['India'] = 'IN'
country_dict['Australia'] = 'AU'
country_dict['Brazil'] = 'BR'
print(country_dict['Australia'])
print(country_dict['Canada'])

Output

AU
Key Not Present
raja
Published on 14-Nov-2018 09:06:52
Advertisements