English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Handling missing keys in Python dictionaries

In Python, there is a container called a dictionary. In the dictionary, we can map keys to their values. Using a dictionary allows us to access values in constant time. However, if the given key does not exist, some errors may occur.

In this section, we will see how to handle such errors. If we try to access a missing key, we may return such an error.

Example Code

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

Output Result

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'

usingget()Method handles KeyError

We can use the get method to check the key. This method has two parameters. The first is the key, and the second is the default value. After finding the key, it will return the value associated with the key, but if the key does not exist, it will return the default value, which is passed as the second parameter.

Example Code

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

Output Result

AU
Not Found

usingsetdefault()Method handles KeyError

methodsetdefault()method is similar to theget()method. It also requires two parameters, for exampleget(). The first is the key, and the second is the default value. The only difference with this method is that when a key is missing, it will add a new key with the default value.

Example Code

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 Result

AU
Not Present

Using defaultdict

defaultdict is a container. It is located in Python's collections module. defaultdict uses the default factory as its parameter. Initially, the default factory is set to 0 (integer). If the key does not exist, it will return the value of the default factory.

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

Example Code

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 Result

AU
Key Not Present