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
def group(rows): groups = {} for key, value in rows: groups.setdefault(key, []).append(value) return dict(groups)from collections import defaultdict
def group(rows): groups = defaultdict(list) for key, value in rows: groups[key].append(value) return dict(groups)