Defaultdict in Python with Examples

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

The defaultdict is a subclass of dict which is available in the Collections module. It is a dictionary type that allows us to set default values to keys. Unlike typical dictionaries, defaultdict returns a default value for the missing keys.

Creating Python defaultdict

To create a defaultdict, we need to import the defaultdict class from the collections module. To do that, we can use the following line of code.

Example of importing the defaultdict in Python

from collections import defaultdict

The defaultdict takes a function as an argument to return values for missing keys. So let us define a function that returns a default value.

Example of defining a function for defaultdict in Python

def geeks():

    return "PythonGeeks"

Using the imported class and the function we defined, we can go ahead and create defaultdict objects. To create a defaultdict object, we use the following syntax.

Syntax

defaultdict(default_factory=None, /[, ...])

Example of using defaultdict in Python

from collections import defaultdict
def geeks():
    return "PythonGeeks"

my_dict = defaultdict(geeks)
my_dict["Name"] = "Lisa"
my_dict["Age"] = 20

print(my_dict)

Output

defaultdict(<function geeks at 0x10fc50280>, {‘Name’: ‘Lisa’, ‘Age’: 20})

In the above code example, we created a defaultdict called my_dict and defined two key-value pairs.

Accessing values of defaultdict

Accessing the values of the already defined keys of the defaultdict returns their respective values.

Example of accessing defined keys of defaultdict in Python

print(my_dict["Name"])
print(my_dict["Age"])

Output

Lisa20

The defaultdict returns the default value when we try to access the value of a missing key.

Example of accessing undefined keys of defaultdict in Python

print(my_dict["Hobbies"])

Output

PythonGeeks

In the above code example, the key “Hobbies” is not defined as the defaultdict. So the defaultdict returned the default value obtained from the function geeks that we passed when creating the defaultdict object.

When we access the value of a missing key, defaultdict creates a new key-value pair with the missing key and the default value.

Example of defaultdict in Python

from collections import defaultdict
def geeks():
    return "PythonGeeks"

my_dict = defaultdict(geeks)
print(my_dict.keys()) # empty defaultdict
my_dict["Name"] = "Lisa"
my_dict["Age"] = 20
print(my_dict.keys()) # defined keys
print(my_dict["Hobbies"]) # accessing a missing key
print(my_dict.keys()) # adds the missing key "Hobbies"
print(my_dict)

Output

dict_keys([])dict_keys([‘Name’, ‘Age’])

PythonGeeks

dict_keys([‘Name’, ‘Age’, ‘Hobbies’])

defaultdict(<function geeks at 0x10067b5e0>, {‘Name’: ‘Lisa’, ‘Age’: 20, ‘Hobbies’: ‘PythonGeeks’})

Using Lambda Functions with defaultdict

We can shorten our code by using the lambda function when defining a defaultdict object. To understand this, let us define a defaultdict that stores the country of origin of employees in a US-based company. Since most employees come from the same country as the company, let us also define the value “USA” as the default value of the defaultdict.

Example of defaultdict in Python

from collections import defaultdict
emp_origin = defaultdict(lambda : "USA")
emp_origin["Munna"] = "India"
print(emp_origin["Munna"])
print(emp_origin["Jackson"])

Output

IndiaUSA

In the above code example, we used the lambda function to set a default value for defaultdict.

__missing__(key)

We can use the magic method __missing__(key) to access the default value of missing keys.

Example of using __missing__() in Python

from collections import defaultdict

learning_sites = defaultdict(lambda : "PythonGeeks")
print(learning_sites.__missing__("Python"))

Output

PythonGeeks

In the above code example, since the key “Python” is missing, defaultdict returned the default value “PythonGeeks”.

Usually, This method is invoked by another magic method __getitem__() when the key we try to access is not defined in the dictionary.

Example of using __getitem__() in Python

from collections import defaultdict
learning_sites = defaultdict(lambda : "PythonGeeks")
print(learning_sites.__getitem__("Python"))

Output

PythonGeeks

Passing Data Types to defaultdict in Python

Instead of defining a function to use as a defaultfactory, we can use various data types as a defaultfactory to our defaultdict. Let us see some of those data types.

Using the List as a defaultfactory

In place of a function, we can pass the list as an argument to defaultdict. This sets an empty list as the default value of all elements.

Example of using defaultdict in Python

from collections import defaultdict
d = defaultdict(list)
d["companies"].append("Apple")
d["companies"].append("Samsung")
print(d)
print(d["names"]) # missing key

Output

defaultdict(<class ‘list’>, {‘companies’: [‘Apple’, ‘Samsung’]})[]

Using the int as a defaultfactory

Passing the int as an argument sets the integers 0 as the default value of all elements.

Example of using defaultdict in Python

from collections import defaultdict
d = defaultdict(int)
d["scores"] += 1
d["scores"] += 1
print(d)
print(d["names"]) # missing key

Output

defaultdict(<class ‘int’>, {‘scores’: 2})0

Using the float as a defaultfactory

Passing the float as an argument sets the floating-point value 0.0 as the default value of all elements.

Example of using defaultdict in Python

from collections import defaultdict
d = defaultdict(float)
d["mean"] = 3.5
d["median"] += 2.34
print(d)
print(d["mode"]) # missing key

Output

defaultdict(<class ‘float’>, {‘mean’: 3.5, ‘median’: 2.34})0.0

Python Interview Questions on Python defaultdict

Q1. Create an empty dictionary that prints a value 5 when any key is called.

Ans 1. Complete code is as follows:

from collections import defaultdict
def default_value():
    return 5

d = defaultdict(default_value)

print(d[1])

Output

5

Q2. Create a defaultdict with default value “Hello”.

Ans 2. Complete code is as follows:

from collections import defaultdict
def default_value():
    return "Hello"

d = defaultdict(default_value)

print(d["A"])

Output

Hello

Q3. Create a defaultdict with default value 100. The keyword def should not be used.

Ans 3. Complete code is as follows:

from collections import defaultdict

d = defaultdict(lambda: 100)

print(d[0])

Output

100

Q4. Create a defaultdict with an empty tuple as the default value of all keys.

Ans 4. Complete code is as follows:

from collections import defaultdict
d = defaultdict(tuple)

print(d[0])

Output

()

Q5. Create a defaultdict by using int as a defaultfactory.

Ans 5. Complete code is as follows:

from collections import defaultdict
d = defaultdict(int)

print(d["hello"])

Output

0

Conclusion

In this article, we learned how to create defaultdicts and how to use them. We also learned about different data types that can be used as default values. Furthermore, please express any questions or concerns in the comments area.

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google | Facebook


Leave a Reply

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