What is DefaultDict in Python?
The defaultdict is similar to a dictionary in Python. It is a type of container present inside the collections module. It inherits its properties from the dict class. The primary importance of the defaultdict in Python is that it does not throw an error when a non-existent key is accessed. We can provide a default value for a key that does not exist in the dictionary.
Syntax:
defaultdict(default_factory)
Parameter:
The default_factory function: We can set a default value to a dictionary using this function. This argument is necessary. If it is absent, the dictionary will throw an error.
Let us consider one example.
Code:
from collections import defaultdict
# we define the default_factory function here
def default_factory():
return "The Key is not defined"
# Defining the dict
# We call the default_factory function inside the default dict
letters = defaultdict(default_factory)
letters["x"] = 1
letters["y"] = 2
print(letters["x"])
print(letters["y"])
print(letters["z"])

You can also try this code with Online Python Compiler
Run Code
Output:
1
2
The Key is not defined
The default_factory function can accept lists and integers as arguments. Our dictionary behaves a little differently with each argument. Let us see how to use these arguments.
You can practice by yourself with the help of online python compiler for better understanding.
Using List as default_factory
While defining a defaultdict in Python, we can pass a list class as an argument to the defualt_factory function. The dictionary now created will have values in the form of a list. If a non-existing key is accessed, then the dictionary will return an empty list.
Consider this example:
Code:
from collections import defaultdict
dict1 = defaultdict(list)
dict1['A'].append(1)
dict1['B'].append(2)
dict1['A'].append('lokesh')
dict1['D']
print(dict(dict1.items()))

You can also try this code with Online Python Compiler
Run Code
Output:
{'A': [1, 'lokesh'], 'B': [2], 'D': []}
dict1['A'].append(1) means an empty list is created by default with the key ‘A’. One is appended to this list.
Using Int as default_factory
When the int class is passed as a default, the defaultdict in Python is created with the default value of zero. This statement means that any non-existent key, when accessed, will show the value 0.
Let us consider one example. Suppose we have a list of integers, and we are interested in counting the occurrence of each number. Here we can use int as default_factory.
Code:
from collections import defaultdict
countOccurence = defaultdict(int)
Array = [10, 12, 13, 10, 12, 99, 13, 22, 10]
for i in Array:
countOccurence[i] += 1
print(countOccurence)

You can also try this code with Online Python Compiler
Run Code
Since the default value of every key initially is zero, we increment the value of a key by one every time we encounter it.
Output:
defaultdict(<class 'int'>, {10: 3, 12: 2, 13: 2, 99: 1, 22: 1})
Using Set as default_factory
If we pass a list as default to the default_factory, a dictionary of sets is created. So if you assign multiple values to a key, they will form a set. An empty key, that is a non-existent key is assigned an empty set.
Code:
from collections import defaultdict
set_dict = defaultdict(set)
set_dict['one'].add(1)
set_dict['one'].add(2)
set_dict['one'].add(3)
set_dict['two']
print(dict(set_dict.items()))

You can also try this code with Online Python Compiler
Run Code
Output:
{'one': {1, 2, 3}, 'two': set()}
Let us now understand the internal working of defaultdict in Python.
Inner Working of DefaultDict
As mentioned above, the defaultdict is a subclass of the dictionary class. It contains all the standard dictionary operations. Along with these operations, it also adds a method and an instance variable to its functioning. The method is called __missing__ method, and the variable is termed default_factory.
Actually, the defaultdict data type calls the default_factory variable. This variable provides the default value. But if we see the in-depth work, we will find that the __missing__ method provides the default value. The default_factory that was passed as a parameter to the defaultdict is also passed to the __missing__ method.
The __missing__ method is called by another method named as __getitem__() method. The __getitem__() method is called when the dictionary cannot find the requested key.
Note that it is necessary to provide the default_factory argument, or else the code will throw a KeyError.
Let us understand with an example:
Code:
from collections import defaultdict
# Here the 'lambda' function
# is the default_factory
empCity = defaultdict(lambda: "Employee not found")
empCity["rahul"] = "Bangalore"
empCity["varun"] = "Indore"
empCity["shreya"] = "Ranchi"
# The __missing__ method provides
# the default value of a key
print(empCity.__missing__('rahul'))
print(empCity.__missing__('shreya'))

You can also try this code with Online Python Compiler
Run Code
Output:
Employee not found
Employee not found
Even though the keys ‘rahul’ and ‘shreya’ existed, the __missing__() method only returned the default value which we set while defining the dictionary.
Frequently Asked Questions
What is the main difference between a dictionary and a defaultdict in Python?
The main difference between a dictionary and a defaultdict in Python is that you cannot access non-existent keys in an ordinary dictionary. However, the defaultdict in Python allows us to create dictionaries having a default value.
How can we remove a particular key from a dictionary?
We can remove a specific key from a dictionary using the pop() method. This method takes that particular key as an argument, and the method removes the key from the dictionary.
Can we create a copy of a dictionary?
We cannot copy a dictionary by directly equating two directories, like dictA = dictB. This is because equating creates a reference dictionary. We can use the copy() method to copy a dictionary.
For example, dictA = dictB.copy().
Conclusion
In this article, we learned about the defaultdict in Python. We discussed its inner working and considered some examples. The defaultdict is a subclass of the dictionary class. The primary importance of the defaultdict in Python is that it does not throw an error when a non-existent key is accessed.
We hope you enjoyed reading this article.
You can refer to this fantastic article by coding ninjas to learn more about Python. We also suggest you check out our course on Python.
Also check out - Data Dictionary In Software Engineering
Visit our website to read more such blogs. Make sure you enroll in our other courses as well. You can take mock tests, solve problems, and interview puzzles. Also, you can check out some exciting interview stuff- interview experiences and an interview bundle for placement preparations. Do upvote our blog to help fellow ninjas grow.