15. Updating dictionaries

The key is to avoid copying and updating dictionaries just to override values. ChainMap will take care of this concern. Notice how the discouraged approached copies d1 then updates with d2, while ChainMap starts with d2 followed by d1. This part of the ChainMap is awkward.

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

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