Member-only story
Python ChainMap: Treat Multiple Dictionaries as One
Practical use cases of ChainMap with easy to follow examples for beginners
You’ve probably never heard of ChainMap before. ChainMap is another lesser-known data container provided in the Python collections module.
In this article, I will try to explain ChainMap and its use cases. Once you finished reading it, you will hopefully get an understanding on how ChainMap helps to solve some of the specific problems you may have when coding.
What is ChainMap?
In a nutshell, it allows you to treat multiple dictionaries as one. It groups multiple dictionaries by providing a single and update-able view over multiple dictionary objects.
Let’s consider that we have books in our library and we would like to store them in a dictionary object with author-title pairs. Instead of storing them all in a single dictionary object, we can group the books with similar genres and store them in separate dictionary objects. Then, they can be contained in a ChainMap object.
from collections import ChainMapthriller = {'L.Foley': 'The Guest List', 'T.Fisher ': 'The Wives'}
romance = {'E.Henry': 'Beach Read', 'A.Hall': 'Boyfriend Material'}
science_fiction = {'M.Wells'…