Python Snippet

defaultdict for Implicit Init

Difficulty: Easy

`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.

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

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.