+

Handling Missing Keys in Python Dictionaries &Dictionary container

Python has one container called Dictionary. In dictionaries, we can map keys to its value. Using a dictionary, values ​​can be accessed at a constant time. But when these keys are not available, some errors may occur.

In this section, we will see how to handle these kinds of errors. If we are trying to access missing keys, it can lead to errors like this. 

Sample Code

 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) & lt; ipython-input-2-a91092e7ee85 & gt; in & lt; module & gt; () 2 3 print (country _dict [`Australia`]) ---- & gt; 4 print (country_dict [`Canada`]) # This will return error KeyError:` Canada` 

Using the get () method to handle the KeyError

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




Sample code

 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 () to handle KeyError

This method setdefault () is similar to get () method. It also takes two arguments like get (). The first &this is the key, and the second &default value. The only difference with this method is that if the key is missing, it adds new keys with a default value.

Sample 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

 AU Not Present  

Using defaultdict

Defaultdict &it is a container. It is located in the collections module in Python. Defaultdict takes a default factory as an argument. Initially, factory default is 0 (integer). When the key is not present, it returns the default factory value.

We don`t need to specify methods over and over again, so it provides a faster method for dictionary objects.

Sample 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 (cou ntry_dict [`Australia`]) print (country_dict [` Canada`])  

Output

 AU Key Not Present 

< br>

Get Solution for free from DataCamp guru