Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

Python · Class

defaultdict

defaultdict is a dict subclass that creates and stores a value for an absent key by calling a configured zero-argument factory. It is useful for grouping, counting, and collecting distinct values without pre-initializing every key.

How it works

A defaultdict behaves like a dict but supplies a value for a missing key by calling its default_factory without arguments, storing that value under the key, and returning it. The factory is selected when the object is constructed and can also be changed later.

Syntax

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

Parameters

NameTypeDescription
default_factorycallable | NoneA callable invoked without arguments for an absent key, or None; it initializes default_factory.
...mapping or iterable, plus keyword argumentsOptional positional and keyword data accepted as by the dict constructor.

Returns

A new dictionary-like object.

Key points

  • It retains normal dictionary operations while adding automatic handling for missing keys.
  • Construction chooses the callable used to create defaults, or disables that behavior with None.
  • The factory receives no key or other arguments.
  • The generated value both becomes the mapping entry and becomes the lookup result.
  • list factories provide convenient per-key collections for grouping.
  • An int factory supplies zero, making increments work for unseen keys.
  • A set factory supports collecting distinct values separately for each key.

Common mistakes

  • A missing key raises KeyError when default_factory is None.
  • get() does not invoke the factory, so it can return None for an absent key.
  • Exceptions from the factory are passed through unchanged.

Example: Count values with a factory

from collections import defaultdict

words = ["api", "db", "api", "cache"]
counts = defaultdict(int)
for word in words:
    counts[word] += 1

print(dict(counts))

A missing key starts at zero because int is the factory; incrementing then records each word's frequency.

When to use it

Grouping records

Accumulate multiple values under each key without checking whether a list exists.

Counting frequencies

Increment per-key totals while unseen keys begin at zero.

Building indexed sets

Collect unique per-key values while automatically creating empty sets.

Interview questions

QWhat is defaultdict?

defaultdict is a dict subclass that adds the writable default_factory attribute and customizes missing-key handling. Other dict behavior remains the same.

Follow-up: What happens when the factory is None? A missing-key access raises KeyError with the requested key.

QHow does missing-key lookup work?

On a missing-key lookup, __missing__ calls default_factory with no arguments, inserts the returned value under that key, and returns it. If the factory is None, it raises KeyError.

Follow-up: Does get() use this behavior? No; get() follows normal-dict behavior and returns None unless an explicit default is supplied.

QHow is a defaultdict constructed?

The first positional argument initializes default_factory, defaulting to None; remaining positional and keyword arguments are handled like dict construction. The factory must therefore be callable without arguments when used.

Follow-up: Can the factory be changed later? Yes, default_factory is a writable instance attribute, so assigning another callable changes subsequent missing-key behavior.

  • collections.Counter
  • dict
  • __missing__
  • default_factory

Source: collections — Container datatypes — Python 3.15.0 documentation. Checked 2026-10-16.