Skip to content
Sarj Code Standards

prefer-defaultdict

Use defaultdict(list) for a locally owned list-grouping dictionary.

Why

setdefault(key, []) constructs a new empty list on every grouping iteration, including keys already present. A declared list factory keeps initialization in one place and avoids discarded defaults for repeated keys.

Fix

Use collections.defaultdict(list) for this local accumulator and append or extend through groups[key]. Preserve ordering, missing-key behavior and the concrete type at any returned boundary.

Examples

Before — flagged A loop repeats the list default
app/group.py
def group(rows):
groups = {}
for key, value in rows:
groups.setdefault(key, []).append(value)
return dict(groups)
After — preferred The accumulator declares one list factory
app/group.py
from collections import defaultdict
def group(rows):
groups = defaultdict(list)
for key, value in rows:
groups[key].append(value)
return dict(groups)