defaultdict#
collections.defaultdict is a dict that auto-initialises
missing keys with a factory. Saves the setdefault /
get(...) or ... dance.
from collections import defaultdict
by_host = defaultdict(list)
for scan in scans:
by_host[scan.host].append(scan)
counts = defaultdict(int)
for c in text:
counts[c] += 1
The factory is any zero-arg callable: list, dict,
set, int, lambda: 0, lambda: {"port": 80}. The
factory runs only on first access to a missing key.
A defaultdict “is a” dict; pass it anywhere a dict is
expected. The auto-create only kicks in on __getitem__; in
particular defaultdict(list).get(k) returns None for a
missing key without creating it.