3. Updating dictionaries

Avoid copying and updating dictionaries just to override values. ChainMap can layer mappings without creating a merged copy, though the lookup order can be less obvious than a plain dictionary.

Layered mappings can be a better fit when you want override behavior without allocating a brand-new merged dictionary immediately. The main benefit is expressing precedence directly, though it is worth using only when that lookup model is actually helpful.

3.1. Don’t do this

1d1 = {'color': 'red', 'user': 'jdoe'}
2d2 = {'color': 'blue', 'first_name': 'john', 'last_name': 'doe'}
3
4d = d1.copy()
5d.update(d2)

3.2. Do this

1from collections import ChainMap
2
3d1 = {'color': 'red', 'user': 'jdoe'}
4d2 = {'color': 'blue', 'first_name': 'john', 'last_name': 'doe'}
5
6d = ChainMap(d2, d1)