On this page
  1. collections.defaultdict
  2. Import
  3. Signature & Overview
  4. Methods & Attributes
  5. Usage
  6. Gotchas
  7. REPL Inspect

collections.defaultdict

Prev: collections.Counter | Up: collections | Next: collections.deque
Rel: collections.ChainMap, collections.Counter, collections.deque, collections.namedtuple
Ref: docs.python.org — collections.defaultdict
Tags: #public #python3 #stdlib #collections


Import

import collections
from collections import defaultdict

Signature & Overview

collections.defaultdict(default_factory=None, /, [...]) --> dict with default factory

The default factory is called without arguments to produce a new value when a key is not present, in getitem only.

Methods & Attributes

Usage

from collections import defaultdict

groups: defaultdict[str, list[int]] = defaultdict(list)
for key, val in [("a", 1), ("b", 2), ("a", 3)]:
    groups[key].append(val)

assert dict(groups) == {"a": [1, 3], "b": [2]}

Gotchas

REPL Inspect

from collections import defaultdict
help(defaultdict)

Linked from

Related notes