In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it.
Key Features of defaultdict:
- When we access a key that doesn’t exist in the dictionary, defaultdict automatically creates it and assigns it a default value based on a function we provide.
- We need to specify the default value type by passing a function (like int, list or set) when initializing the defaultdict.
Example:
Python
from collections import defaultdict
d = defaultdict(list)
d['fruits'].append('apple')
d['vegetables'].append('carrot')
print(d)
print(d['juices'])
Outputdefaultdict(<class 'list'>, {'fruits': ['apple'], 'vegetables': ['carrot']})
[]
Explanation: This code creates a defaultdict with a default value of an empty list. It adds elements to the ‘fruits’ and ‘vegetables’ keys. When trying to access the ‘juices’ key, no KeyError is raised, and an empty list is returned since it doesn’t exist in the dictionary.
Syntax of DefaultDict in Python
defaultdict(default_factory)
Parameters:
- default_factory: A function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.
Return Value: It returns a dictionary-like object that automatically provides a default value for missing keys, based on the specified callable, instead of raising a KeyError.
How Does defaultdict Work?
When a defaultdict is created, you specify a factory function that will provide the default value for new keys. This factory function could be int, list, str, or any other callable object. For example:
- Using int: If you use int as the factory function, the default value will be 0 (since int() returns 0).
- Using list: If you use list as the factory function, the default value will be an empty list ([]).
- Using str: If you use str, the default value will be an empty string (”).
What is default factory in Python dict?
It is a function returning the default value for the dictionary defined. If this argument is absent then the dictionary raises a KeyError.
Python
from collections import defaultdict
# Defining the dict and passing lambda as default_factory argument
d = defaultdict(lambda: "Not Present")
d["a"] = 1
d["b"] = 2
print(d["a"])
print(d["b"])
print(d["c"])
Use Cases for defaultdict
1. Using List as Default Factory
When the list class is passed as the default_factory argument, then a defaultdict is created with the values that are list.
Python
from collections import defaultdict
d = defaultdict(list)
for i in range(5):
d[i].append(i)
print("Dictionary with values as list:")
print(d)
OutputDictionary with values as list:
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
Explanation: This example demonstrates the use of list as the default factory. A defaultdict is created with list, which means any missing key will automatically have an empty list as its value. The loop appends the value of i to the list of the corresponding key.
2. Using int Default Factory
When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.
Python
from collections import defaultdict
d = defaultdict(int)
a = [1, 2, 3, 4, 2, 4, 1, 2]
for i in a:
d[i] += 1
print(d)
Outputdefaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
Explanation: This example uses int as the default factory. int() returns 0, so missing keys will have a default value of 0. The loop counts the occurrences of each number in the list a and updates the dictionary accordingly.
3. Using str Default Factory
When the str class is passed as the default_factory argument.
Python
from collections import defaultdict
# Using str as the factory function
sd = defaultdict(str)
sd['greeting'] = 'Hello'
print(sd)
Outputdefaultdict(<class 'str'>, {'greeting': 'Hello'})
Explanation: This example uses str as the default factory. str() returns an empty string, so missing keys will have an empty string as their default value. A value (‘Hello‘) is explicitly set for the key ‘greeting‘.
Python defaultdict Type for Handling Missing Keys
Defaultdict adds one writable instance variable and one method in addition to the standard dictionary operations. The instance variable is the default_factory parameter and the method provided is __missing__.
This function is used to provide the default value for the dictionary. It takes default_factory as an argument and if this argument is None, a KeyError is raised otherwise it provides a default value for the given key. This method is basically called by the __getitem__() method of the dict class when the requested key is not found. __getitem__() raises or return the value returned by the __missing__(). method.
Python
from collections import defaultdict
d = defaultdict(lambda: "Not Present")
d["a"] = 1
d["b"] = 2
print(d.__missing__('a'))
print(d.__missing__('d'))
OutputNot Present
Not Present
Explanation:
- The defaultdict is initialized with a lambda function that returns “Not Present” for missing keys.
- When the key ‘a‘ is accessed, its value is returned (1), and __missing__ is not called.
- When the key ‘d‘ is accessed (which does not exist), __missing__ is triggered, and the default value “Not Present” is returned.
Similar Reads
Python Collections Module
The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
13 min read
Namedtuple in Python
Python supports a type of container dictionary called "namedtuple()" present in the module "collections". In this article, we are going to see how to Create a NameTuple and operations on NamedTuple. What is NamedTuple in Python?In Python, NamedTuple is present inside the collections module. It provi
8 min read
Deque in Python
A deque stands for Double-Ended Queue. It is a data structure that allows adding and removing elements from both ends efficiently. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.
6 min read
ChainMap in Python
Python contains a container called "ChainMap" which encapsulates many dictionaries into one unit. ChainMap is member of module "collections". Example: # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6} # Defin
3 min read
Python | Counter Objects | elements()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
6 min read
OrderedDict in Python
An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python. OrderedDict vs dict in PythonNote: Starting from Python 3.7, regular dictionaries (dict) also mainta
10 min read
Defaultdict in Python
In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it. Key Features of defaultdict:When we access a key that doesn
6 min read
Collections.UserDict in Python
An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For mo
2 min read
Collections.UserList in Python
Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
2 min read
Collections.UserString in Python
Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: C/C++ Code # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks Worl
2 min read