Dictionaries also known as maps are data structures that are used a lot in different scenarios. The process of getting an element from a dictionary can be done using an element that is not part of the dictionary which results in an error.

For example, let us take this scenario where we have a dictionary that has an element with the key name and another one with the element surname. If we want to access it using another element, such as age, we are going to see an error like the following:

 my_dictonary = {"name": "Name", "surname": "Surname"}
 print(my_dictonary["age"])  

Here it’s the error thrown:

-KeyError: ‘age’

This can be a source of bugs and many problems that may occur especially if your Python script is part of an application that is running in production.

We can avoid such errors using defaultdict() which does not throw an error when trying to get an element of a dictionary using a key:

 from collections import defaultdict
 ​
 my_dictonary = defaultdict(str)
 my_dictonary['name'] = "Name"
 my_dictonary['surname'] = "Surname"
 ​
 print(my_dictonary["age"])  

That’s basically it.

I hope you find this useful.