collections.defaultdict

A dictionary that creates a default value on its own for a missing key, e.g. an empty list or zero.

Returns
A defaultdict object, that is a dictionary with automatic default values.
On this page

Example

#
Python
from collections import defaultdict

topics = [("HTML", "tags"), ("CSS", "flexbox"), ("HTML", "forms")]

by_course = defaultdict(list)
for course, topic in topics:
    by_course[course].append(topic)

print(by_course["HTML"])
print(dict(by_course))
Resultsaved result, you can check it
['tags', 'forms']
{'HTML': ['tags', 'forms'], 'CSS': ['flexbox']}

Definition and usage

#

The defaultdict class from the collections module works like an ordinary dictionary, but when you read a missing key it does not raise KeyError. Instead, it calls the function given at creation, stores the result under that key, and returns it.

You pass the function without parentheses: defaultdict(list) creates an empty list for new keys, defaultdict(int) zero, and defaultdict(set) an empty set. You can also pass your own function, e.g. defaultdict(lambda: "none").

The most common uses are grouping (groups[key].append(item)) and summing (totals[key] += value) without checking whether the key already exists. Remember that simply reading d[key] also adds the missing key. The get() method and the in operator do not.

Syntax

#
Syntax
from collections import defaultdict

defaultdict(default_factory)
defaultdict(list)
defaultdict(int)

Parameters

#
  • default_factory

    function with no arguments, or None

    Creates the value for a missing key, e.g. list gives [], and int gives 0. With None, the dictionary behaves like an ordinary dict.

More examples

#
Summing with int
Python
from collections import defaultdict

points = defaultdict(int)
for name, exp in [("Emma", 20), ("Jack", 15), ("Emma", 10)]:
    points[name] += exp

print(points)
print(points["Mia"])
Resultsaved result, you can check it
defaultdict(<class 'int'>, {'Emma': 30, 'Jack': 15})
0
A trap: reading also creates a key
Python
from collections import defaultdict

scores = defaultdict(list)
print(scores["Mia"])
print("Mia" in scores, len(scores))

print(scores.get("Zoe"), len(scores))
Resultsaved result, you can check it
[]
True 1
None 1

Good practices

#
  • To check whether a key exists, use in or get(). Reading through square brackets will add the missing key.
  • Before passing the result on, convert it to an ordinary dictionary with dict(). It prints more clearly, and an accidental read of a missing key will no longer add a new entry.
  • For simply counting items, Counter is even more convenient.

Related entries

#

Spotted a mistake or missing an example? Write to us.