Python Chainmap In Collections Tutorial – Complete Guide

Welcome to this exciting tutorial where we dive into the world of Python ChainMap in collections. If you’re looking to take your Python coding skills to the next level, or just starting out on your programming journey, learning about ChainMap is absolutely essential. This powerful tool helps you manage multiple dictionaries and elevates your ability to handle complex data structures.

What is Python ChainMap in Collections?

A ChainMap in Python consolidates multiple dictionaries into a single unit while maintaining their original order. It is part of Python’s built-in library, Collections, which provides alternatives to built-in container data types like tuples, lists, and dictionaries.

Why Learn about ChainMap?

Mastering the utilization of ChainMap in Python accomplishes two major goals:

  • It greatly simplifies the management of multiple dictionaries in your code.
  • It promotes efficiency and enhances code readability, making your code cleaner and more optimal.

Now that we’ve introduced Python ChainMap and its importance, let’s delve right into the coding tutorial.

CTA Small Image

Coding with Python ChainMap: Part 1

Let’s start this journey by importing the ChainMap from collections.

from collections import ChainMap

Next, we’ll create two dictionaries with some sample content.

dict1 = {'Name': 'John', 'Age': 25}
dict2 = {'Country': 'USA', 'Job': 'Engineer'}

Now, we will combine them using ChainMap.

chain = ChainMap(dict1, dict2)

The output represents both dictionaries within a ChainMap: ChainMap({'Name': 'John', 'Age': 25}, {'Country': 'USA', 'Job': 'Engineer'}). This is our very first Python ChainMap instance!

Coding with Python ChainMap: Part 2

Moving on, let’s explore some handy operations we can perform with ChainMap. One fundamental operation is accessing the elements.


This code directly retrieves the value associated with ‘Name’ from our ChainMap instance.

The ChainMap behaves as a stack where it searches key from left to right.

dict1 = {'Name': 'John', 'Age': 25}
dict2 = {'Name': 'Emma', 'Country': 'USA'}
chain = ChainMap(dict1, dict2)
print(chain['Name']) # Outputs: John

Let’s explore adding a new dictionary to the existing ChainMap:

dict3 = {'Hobby': 'Reading', 'Gender': 'Male'}
new_chain = chain.new_child(dict3)
print(new_chain) # Outputs: ChainMap({'Hobby': 'Reading', 'Gender': 'Male'}, {'Name': 'John', 'Age': 25}, {'Name': 'Emma', 'Country': 'USA'})

Here we created a new dictionary (dict3) and used the new_child() method to add it as a new child dictionary in our ChainMap. This approach is key to managing dynamic and growing data structures within your code.

More Coding with Python ChainMap

While ChainMap allows simple merging of dictionaries, it also introduces methods to conveniently and efficiently handle merged dictionaries.

The keys() method in ChainMap returns a list of all keys present in the added dictionaries.

print(new_chain.keys()) # Outputs: KeysView(ChainMap({'Hobby': 'Reading', 'Gender': 'Male'}, {'Name': 'John', 'Age': 25}, {'Name': 'Emma', 'Country': 'USA'}))

Similarly, the values() method will give us all the values.

print(new_chain.values()) # Outputs: ValuesView(ChainMap({'Hobby': 'Reading', 'Gender': 'Male'}, {'Name': 'John', 'Age': 25}, {'Name': 'Emma', 'Country': 'USA'}))

See how we can fetch keys and values across all dictionaries at once? This is the power of ChainMap at play!

What about updating the value of a key? It’s quite easy, you simply assign a new value to the key, like you’d do in a dictionary:

new_chain['Name'] = 'Mike'
print(new_chain) # Outputs: ChainMap({'Hobby': 'Reading', 'Gender': 'Male', 'Name': 'Mike'}, {'Name': 'John', 'Age': 25}, {'Name': 'Emma', 'Country': 'USA'})

Notice how the value associated with ‘Name’ in the first dictionary has changed to ‘Mike’.

And as a final trick, ChainMap.reversed() allows us to reverse the order of our dictionaries:

reversed_chain = ChainMap.reversed(new_chain)
print(list(reversed_chain)) # Outputs: [{'Name': 'Emma', 'Country': 'USA'}, {'Name': 'John', 'Age': 25}, {'Hobby': 'Reading', 'Gender': 'Male', 'Name': 'Mike'}]

This might be especially useful when order matters in your operations or you want to prioritize some dictionaries over others.

As you can see, Python ChainMap holds immense potential to make your code more organized, readable, and efficient. It’s a perfect tool to have in your Python arsenal.

Where to Go Next with Python?

If you’ve found the power of Python and ChainMap enlightening and want to continue on your journey into the world of Python, Zenva offers resources that cater to all your learning needs.

We encourage you to explore our Python Mini-Degree, which is a comprehensive course designed for both newcomers and seasoned coders. This course covers an extensive array of topics, including coding basics, object-oriented programming, game development and the creation of real-world apps.

Python is renowned for its simplicity, versatility and boasts an impressive selection of libraries. It’s used in a variety of industries including data science, machine learning, space exploration, and robotics.

Our courses, taught by experienced programmers certified by industry leaders like Unity Technologies and CompTIA, are flexible and accessible 24/7 to fit your schedule. You get to reinforce your learning through coding challenges and quizzes, earn completion certificates, and gain skills you can take straight into job applications, game publishing, or even starting a business.

Perhaps you’ve been struck by Python fever and are looking to delve deeper into this versatile language. For a broader collection of Python-themed tutorials and courses, be sure to check out our full catalog of Python courses.


Throughout this tutorial, you’ve learned about the power of Python ChainMap, seen its potential to simplify code, and discovered its efficiency in handling complex data structures. By embracing this element of Python’s Collections library, you’re taking a step towards more streamlined, optimal coding.

So, what’s next? Keep the momentum going, fellow coder! Fuel your programming journey with Zenva’s Python Mini-Degree, where we guide you from beginner to professional coder. Join us today and harness the power of Python to build translations, games, and real-world applications like a pro. Let’s conquer the coding world together!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.