13. Default dictionary values: defaultdict

The key is to avoid checking to see if a key exists in the dictionary, and if not, then initialize its associated value. The use of defaultdict will initialize a value associated with a key that does not yet exists upon first access. Check out itertools too.

13.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)

13.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)}