Merging dictionaries

suggest change

Consider the following dictionaries:

>>> fish = {'name': "Nemo", 'hands': "fins", 'special': "gills"}
>>> dog = {'name': "Clifford", 'hands': "paws", 'color': "red"}

Python 3.5+

>>> fishdog = {**fish, **dog}
>>> fishdog
{'name': 'Clifford', 'hands': 'paws', 'special': 'gills', 'color': 'red'}

As this example demonstrates, duplicate keys map to their lattermost value (for example “Clifford” overrides “Nemo”).

Python 3.3+

>>> from collections import ChainMap
>>> dict(ChainMap(fish, dog))
{'name': 'Nemo', 'hands': 'fins', 'color': 'red', 'special': 'gills'}

With this technique the foremost value takes precedence for a given key rather than the last (“Clifford” is thrown out in favor of “Nemo”). dict() walks the maps from last to first, so a key that appears only in a later map is inserted before untouched keys from an earlier map.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents