Back to Study Material Python

Defaultdict

defaultdict is a dictionary subclass from the collections module that provides a default value for missing keys, eliminating the need to check whether a ke...

Defaultdict

What is defaultdict?

defaultdict is a dictionary subclass from the collections module that provides a default value for missing keys, eliminating the need to check whether a key exists before using it. from collections import defaultdict; d = defaultdict(int). When you access a key that does not exist, defaultdict automatically creates it with the value returned by calling the default factory. defaultdict(int) creates new keys with value 0; defaultdict(list) creates new keys with an empty list; defaultdict(set) with an empty set.

Common Default Factories

The argument to defaultdict is a callable (a factory function) called with no arguments to produce default values. int gives 0. list gives []. set gives set(). float gives 0.0. str gives "". You can also pass a custom lambda: defaultdict(lambda: "N/A") defaults to the string "N/A". Any zero-argument callable works. defaultdict(dict) creates nested dictionaries automatically, enabling d["outer"]["inner"] = value without first creating d["outer"].

Grouping with defaultdict

The most common use of defaultdict is grouping: groups = defaultdict(list); for item in data: groups[item.category].append(item). Without defaultdict you would write: if item.category not in groups: groups[item.category] = []; groups[item.category].append(item). The defaultdict version is cleaner and less error-prone. This pattern is used constantly for building inverted indexes, grouping database results, and categorising any data.

Counting with defaultdict

defaultdict(int) is useful for counting: counts = defaultdict(int); for char in "hello": counts[char] += 1. Because missing keys default to 0, the += 1 works immediately without initialisation. The result is Counter-like but without Counter's extra methods. For pure counting tasks, Counter is often preferred because of most_common() and arithmetic operations. Use defaultdict(int) when you want a counting dict that also supports arbitrary other operations naturally.

Nested defaultdicts

You can nest defaultdicts to create multi-level automatic key creation: tree = defaultdict(lambda: defaultdict(int)). tree["fruits"]["apple"] += 1 works without any initialisation. This is useful for two-dimensional frequency tables or adjacency lists in graph problems. Alternatively, defaultdict(dict) creates a one-level-deep nesting. For very deep nesting, a recursive factory (from a class or a named function) is cleaner than chained lambdas.

Exam Tip

Key defaultdict facts for exams: the default_factory is stored in the __missing__ method — it is called when a key is not found. What is the difference between d.get(key, default) and defaultdict? d.get() returns the default but does not insert it into the dict; defaultdict inserts the new key with the default value. This insertion behaviour can cause bugs if you accidentally access non-existent keys. To prevent this, you can set default_factory to None after building the dict, turning it back into a regular dict.