What are ChainMaps and How to Use Them?

In Python3.3 the ChainMap class was added to the collections module. A ChainMap is ideal when you have multiple mappings that you want to consolidate into a single unit. It’s typically much faster than creating an empty dictionary and running multiple update() calls on it. To learn about the inspiration behind ChainMaps read bug report #11089.

Here’s an example of how the ChainMap signature looks:

class collections.ChainMap(*maps)

To get a concise answer of what a map is we can refer to this post on stackoverflow.

We can look at the source code from Cpython and inside a comment it states the following:

/* We accept for the argument either a concrete dictionary object,
 * or an abstract "mapping" object.  For the former, we can do
 * things quite efficiently.  For the latter, we only require that
 * PyMapping_Keys() and PyObject_GetItem() be supported.
 */

Therefore,we can deduce that the minimal interface needed for dict(mapping) to work is .keys() and .__getitem__(). Below is an example of a ChainMap in action.

>>> from collections import ChainMap
>>> west = {'wa': 'washington', 'id': 'idaho', 'ca': 'california'}
>>> east = {'me': 'maine', 'nc': 'north carolina', 'ny': 'new york'}
>>> west_east = ChainMap(west, east)
>>> west_east
ChainMap({'wa': 'washington', 'id': 'idaho', 'ca': 'california'}, {'me': 'maine', 'nc': 'north carolina', 'ny': 'new york'})
>>> for key, value in west_east.items():
            print(key, value)
me maine
nc north carolina
ny new york
wa washington
id idaho
ca california
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.