![]() |
VOOZH | about |
Defaultdict is a subclass of the built-in dict class from the collections module. It automatically assigns a default value to keys that do not exist which means no need to manually check for missing keys and avoid KeyError.
This example shows how a defaultdict automatically creates missing keys with a default empty list.
defaultdict(<class 'list'>, {'fruits': ['apple'], 'vegetables': ['carrot']})
[]
Explanation:
defaultdict(default_factory)
Parameters:
Return Value: It returns a dictionary-like object that automatically supplies a default value for missing keys instead of raising KeyError.
In a normal dictionary, accessing a missing key raises a KeyError. defaultdict solves this by:
When you create a defaultdict, you specify a default_factory (a callable).
For example:
This mechanism avoids errors and makes code simpler when handling missing keys.
When the list class is passed as the default_factory argument, a defaultdict is created in which the values are lists.
Example: This example shows how we can use list as the default factory, so every missing key will automatically start with an empty list.
Dictionary with values as list:
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
Explanation: 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.
When the int class is passed as the default_factory argument, then a defaultdict is created with default value as zero.
Example: This example demonstrates using int as the default factory, making missing keys default to 0.
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
Explanation: 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.
With defaultdict(str), any new key automatically maps to '', so you can concatenate text without key checks.
Example: This example shows how str as a factory creates empty strings ("") for missing keys.
defaultdict(<class 'str'>, {'greeting': 'Hello'})
Explanation: 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'.
defaultdict is very handy in text processing, for example grouping words by their starting letter.
Example: This example demonstrates how defaultdict(list) can be used to group words by their first letter, very useful in text processing.
defaultdict(<class 'list'>, {'a': ['apple', 'ant'], 'b': ['banana', 'bat'], 'c': ['carrot', 'cat']})
Explanation: Here, defaultdict(list) automatically creates an empty list for each new first letter, so we can group words without checking if the key exists.
Behind the scenes, defaultdict uses the special __missing__() method:
Example: This example shows how the __missing__() method works behind the scenes in defaultdict. It is automatically called when a key is not found, returning the default value instead of raising a KeyError.
Not Present Not Present 1
Explanation:
Note: __missing__() is intended for internal use in defaultdict. To safely access values, use d[key] or d.get(key, default) instead of calling __missing__ directly.