Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Data Structures and Functional Tools

collections.defaultdict

Reference for Python collections.defaultdict: dicts that create missing values with a factory, grouping, nested defaults, __missing__ and the lookup side effect.

A defaultdict is a dict that knows how to create a value when you look up a key that is not there. You pass a zero-argument callable (the default factory) such as list, int or set; when d[key] fails, the factory is called, its result is stored under key, and that value is returned.

That makes grouping and counting loops much shorter, because you no longer test if key not in d before every update.

Python
from collections import defaultdict

groups = defaultdict(list)
groups["fruit"].append("apple")

Try it

Python Grouping with a list factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python The lookup side effect and nesting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
defaultdict(default_factory=None, /, *args, **kwargs)
Name Description
default_factory A callable taking no arguments, or None. Called when a key is missing; stored in the attribute of the same name.
*args, **kwargs Anything the dict constructor accepts (a mapping, pairs, keyword arguments).

Return value: a new defaultdict, which supports every dict method.

Raises: TypeError if the first argument is neither callable nor None. A missing key raises KeyError when default_factory is None.

Usage notes

  • Only d[key] triggers the factory. get(), in, and setdefault() do not call it, so d.get(key) still returns None for a missing key.
  • Reading creates the key. Even a lookup you only meant to inspect inserts a default entry. Use key in d or d.get(key) for read-only checks.
  • The factory takes no arguments. To start from a specific value use a lambda: defaultdict(lambda: 100).
  • Mutable defaults are safe here. Each missing key gets its own fresh list() or set(), unlike a shared default argument in a function.
  • Works through __missing__. dict.__getitem__ calls the __missing__() method when a key is absent; defaultdict implements it. You can use the same hook in your own dict subclass.
  • Printing shows the factory: defaultdict(<class 'list'>, {...}). Convert with dict(d) for a plain display, or if you must stop it from creating keys later.
  • Not the same as Counter. For plain counting, Counter adds most_common() and arithmetic; for grouping, defaultdict(list) is the usual tool.
  • Pickling and JSON. A defaultdict with a lambda factory cannot be pickled; json.dumps treats it as a normal dict.