16. Merging dictionaries
Avoid explicit iterations when merging two dictionaries.
16.1. Don’t do this
1name = {
2 'first_name': 'john',
3 'last_name': 'doe'
4}
5address = {
6 'street': '123 main street',
7 'city': 'washington',
8 'state': 'dc',
9 'zip': 20500
10}
11
12person = {}
13for k, v in name.items():
14 person[k] = v
15for k, v in address.items():
16 person[k] = v
16.2. Do this
1name = {
2 'first_name': 'john',
3 'last_name': 'doe'
4}
5address = {
6 'street': '123 main street',
7 'city': 'washington',
8 'state': 'dc',
9 'zip': 20500
10}
11
12person = {**name, **address}