Inspired Python
>>> d = {"name": "Jerry", "last_name": "Seinfeld", "city": "NYC"}
>>> e = {"name": "George", "last_name": "Costanza"}
# Works in Python 3.3+
# But note the reversed order
>>> from collections import ChainMap
>>> dict(ChainMap(e, d))
{'name': 'George', 'city': 'NYC', 'last_name': 'Costanza'}
# Works in Python 3.5+
>>> {**d, **e}
{'name': 'George', 'city': 'NYC', 'last_name': 'Costanza'}
# Works in Python 3.9+
>>> d | e
{'name': 'George', 'city': 'NYC', 'last_name': 'Costanza'}
>>> e | d
{'name': 'Jerry', 'last_name': 'Seinfeld', 'city': 'NYC'}

Python Dictionary Tricks: Merging dictionaries

There are multiple ways of merging dictionaries to create a new one, but Python 3.9 introduces a much easier notation. All methods merge left-to-right, with dictionaries to the right overriding items to the left, with the exception of ChainMap where it is the other way around.

Be Inspired Get Python tips sent to your inbox

We'll tell you about the latest courses and articles.

Absolutely no spam. We promise!