How to Handle Missing Keys in Python Dictionary

We are going to learn about how to handle missing keys in the Python dictionary. Dictionaries are widely used all over. It acts as a container. It gives access to every key to its value.

Most of the time we try to access a key, which is not present in the dictionary. Then we face a missing key error. We can handle those missing key errors in different ways. we will discuss some easy ways of them.

To Handle Missing Keys in Python Dictionary

Suppose we have a dictionary, and we are trying to access a key, which is not present in the dictionary.

a = { 'b' : 5 , 'd' : 8 }
print (a['c'])

Output:

Traceback (most recent call last):
File "C:\b.py", line 2, in <module>
print (a['c'])
KeyError: 'c'

As we can see, it shows a key error. Because we have not set any key named ‘c’ in the dictionary.

To avoid such errors, we will learn five different ways to handle missing keys in the Python dictionary. Such as, Using key in dict, try-except block, get() method, setdefault() method, and defaultdict() method.

Using Key in Dict

It is the basic way to solve key errors using if-else condition. To check if the key is present or not.

ele = {'a': 5, 'c': 8, 'e': 2}
if "d" in ele:
    print(ele["d"])
else:
    print("Key not found")

Output:

Key not found

It is simple to use this. Here the key ‘d’ is not in the dictionary. Hence it prints “Key not found”.

Using Try-Except Block

We can also use try-except block to check the presence of a key.

ele = {'a': 5, 'c': 8, 'e': 2}
try:
    print(ele["d"])
except:
    print("Key not found")

Output:

Key not found

It always works. when the ‘d’ key is not in the dictionary, it will catch the error and show the except part.

Using get() Method

get() method can pass two arguments. The key and default value. If the key is in the dictionary the value will be printed. Otherwise, the default value will be printed.
Syntax: get(key, default_value).

ele = {'a': 5, 'c': 8, 'e': 2}
print(ele.get('d', 'Key Not Found'))
print(ele.get('a', 'Key Not Found'))

Output:

Key Not Found
5

In the above code, the key ‘d’ is not present in the dictionary, it shows ‘Key Not Found’. And as the key ‘a’ is present, it prints ‘5’.

Using setdefault() Method

It works the same as the get() method and passes both key and default value arguments. But when every time a key is not present, it creates a new key with the default value in it.

ele = {'a': 5, 'c': 8, 'e': 2}
ele.setdefault('f', 0)
print(ele['e'])
print(ele['f'])
print(ele)

Output:

2
0
{'a': 5, 'c': 8, 'e': 2, 'f': 0}

Here we can see that a new key ‘f’ is created with the default value ‘0’ in it.

Using defaultdict() Method

Where a normal dictionary gives an error if the key is absent. The defaultdict() function returns the default factory value. It passes only the default factory argument. If it is not set, then integer ‘0’ will be assigned as the default.

import collections
ele = collections.defaultdict(lambda : 'Key not found')
ele['a'] = 5
ele['b'] = 8
print ("'a' is : ",end="")
print (ele['a'])
print ("'d' is : ",end="")
print (ele['d'])

Output:

'a' is : 5
'd' is : Key not found

Note: We need to import collections first. We need to initialize the keys and value in it by assignment way.

This method is faster than other methods we have discussed above.

Thanks for your time!

 

Also read:
To comment out a portion of code in Python
Add space after dot or comma in Python string

Leave a Reply

Your email address will not be published. Required fields are marked *