Code Snippets
/

defaultdict for Implicit Init

defaultdict for Implicit Init

`collections.defaultdict` removes the boilerplate of checking-then-initialising before every increment or append. It supplies a default value when a missing key is read, and that default lives in the dict from then on. This snippet covers the bucket-by-key pattern with `defaultdict(list)`, the count pattern with `defaultdict(int)`, and a nested `defaultdict` for two-level groupings.

Python
Easy
3 snippets
py-collections
py-standard-library
code-template
hash-table

348 views

2

from collections import defaultdict

rows = [
    {'role': 'admin', 'name': 'Ada'},
    {'role': 'member', 'name': 'Bo'},
    {'role': 'admin', 'name': 'Cal'},
    {'role': 'member', 'name': 'Di'},
]

by_role = defaultdict(list)
for row in rows:
    by_role[row['role']].append(row['name'])

print(dict(by_role))
# {'admin': ['Ada', 'Cal'], 'member': ['Bo', 'Di']}

Without defaultdict, the loop body would be if role not in by_role: by_role[role] = [], then by_role[role].append(...). defaultdict(list) collapses that into one line: any read of a missing key auto-creates an empty list and inserts it. The defaultdict constructor takes a factory (here list), called with no arguments to produce the default. Wrap the result in dict() for printing if you want a clean output, since the repr of a defaultdict shows the factory.