Data Structures in Python: ChainMap

Hello, I hope you are following this course from the beginning. With today's tutorial, we are heading towards more and more interesting data structures in python.

Links to previous tutorials are available at the bottom of this article

ChainMap is a data type in Python. It is a container that encapsulates many dictionaries into one unit. The combined dictionaries contain keys and values in specific sequences. The best use of ChainMap is to search through multiple dictionaries at a time and get proper key-value pair. It is often much faster than creating a new dictionary and running multiple update() calls.

Are you confused? Don’t worry, let's implement to get a better idea about this.

Creating a ChainMap

First of all, we have to import ChainMap from the ‘collections’ module:

from collections import ChainMap

Now let's create a ChainMap:

d1 = {'day1': 'Mon', 'day2': 'Tue'}
d2 = {'day3': 'Wed', 'day1': 'Thu'}
c_m = ChainMap(d1, d2)print(c_m)#OUTPUT
ChainMap({'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day1': 'Thu'})

In the above example, we created two dictionaries and then stored those in one ChainMap.


ChainMap supports all usual dictionary methods. In it has a map() method which is used to display keys with corresponding values of all the dictionaries in ChainMap in a stored state. It is a user updatable list mapping.

Let’s see how to use it:

print(c_m.maps) #here we used maps method on c_m and printed it#OUTPUT
[{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Wed', 'day1': 'Thu'}]

Accessing Keys and Values

We can access the list of keys and values using the key() and value() methods in ChainMap.

ks = list(c_m.keys()) # List of keys
['day3', 'day1', 'day2']
vs = list(c_m.values()) #List of values
['Wed', 'Mon', 'Tue']
#Printing all values
for key, value in c_m.items():
print(f"key: {key}, value: {value}")
key: day3, value: Wed
key: day1, value: Mon
key: day2, value: Tue

Here in the above example of accessing the list of keys and values, you should notice that in the list of keys, a duplicate key is removed, and in the list of values value of that duplicate key is removed.


When elements in the dictionary are updated then ChainMap is also instantly updated.

d2['day3'] = 'Sun'print(c_m.maps)#OUTPUT
[{'day1': 'Mon', 'day2': 'Tue'}, {'day3': 'Sun', 'day1': 'Thu'}]

That should be enough for this tutorial I hope you enjoyed this tutorial. See you tomorrow, bye!!


Lecture 1:

Lecture 2:

Lecture 3:

Lecture 4:

Lecture 5:

Lecture 6:

Lecture 7:

Lecture 8:

Lecture 9:

Lecture 10:

Lecture 11:

Lecture 12:

Lecture 13:

Lecture 14:

Lecture 15:

Lecture 16:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store