1. Default dictionary values: defaultdict
Avoid checking whether a key exists before initializing its value. defaultdict creates the default value for a missing key on first access. itertools.groupby can also help in some grouping cases.
That removes repeated existence checks and keeps the happy path focused on the update itself. It is most useful when the default for a missing key is part of the data shape, such as an empty list, set, or counter value.
1.1. Don’t do this
1names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
2
3d = {}
4for name in names:
5 key = len(name)
6 if key not in d:
7 d[key] = []
8 d[key].append(name)
1.2. Do this
1from collections import defaultdict
2
3names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
4
5d = defaultdict(list)
6for name in names:
7 key = len(name)
8 d[key].append(name)
1import itertools
2
3names = ['john', 'jane', 'jeremy', 'janice', 'joyce', 'jonathan']
4
5key = lambda s: len(s)
6d = {k: list(g) for k, g in itertools.groupby(sorted(names, key=key), key)}