Home

defaultdict

defaultdict is a dict-like container from Python's collections module that provides a default value for missing keys via a factory function passed at construction time. If a key is accessed that is not present, defaultdict automatically creates a value by calling the default_factory and inserts the key with that value, returning it. This behavior contrasts with a standard dict, which raises KeyError for missing keys. If default_factory is None, defaultdict behaves like a regular dict.

Common factories include int (for counting, because int() returns 0), list (to collect items for each key),

Usage examples: d = defaultdict(list); d['a'].append(1) results in {'a': [1]} without KeyError. For counting occurrences, d = defaultdict(int);

Compared to pure dict, defaultdict reduces code for missing-key handling, especially in grouping and accumulation tasks.

and
set
(to
accumulate
unique
items).
The
default_factory
can
be
changed
after
creation.
for
x
in
data:
d[x]
+=
1.
It
is
not
appropriate
when
a
missing
key
should
be
allowed
to
raise
an
exception
or
when
you
need
explicit
KeyError
semantics;
in
such
cases,
use
a
normal
dict
or
handle
missing
keys
differently.
It
is
often
used
in
data
processing
tasks,
such
as
grouping,
bucketing,
or
building
inverted
indices.
It
is
part
of
the
standard
library
and
coexists
with
other
collections
like
Counter.