TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Member-only story

Python ChainMap: Treat Multiple Dictionaries as One

3 min readOct 3, 2021

--

Photo by Brandon Mowinkel on Unsplash

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'…

--

--

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Erdem Isbilen
Erdem Isbilen

Written by Erdem Isbilen

Machine Learning and Data Science Enthusiasts, Automotive Engineer, Mechanical Engineer, https://www.linkedin.com/in/erdem-isbilen/

No responses yet