← Back to list

Advanced Dictionary Operations with ChainMap

In Python, there’s a fascinating feature called ChainMap, available in the collections module. This feature combines dictionaries without…

Naveen Pandey in Python in Plain English · 2025-01-06 04:29 · 66 claps · 2.0 min read paywalled
#chainmap #python #coding #programming-languages #advance-python
Open on Medium ↗
Wiki topics: 💻 · Programming

Advanced Dictionary Operations with ChainMap

In Python, there’s a fascinating feature called ChainMap, available in the collections module. This feature combines dictionaries without overwriting or replacing values, offering flexibility and control. Below, we explore its functionality and utility with examples.

Image by Author

Image by Author

Importing ChainMap

To use ChainMap, you must import it from the collections module:

from collections import ChainMap

Combining Dictionaries

Normally, when combining dictionaries, duplicate keys are overwritten. For instance:

# Two dictionaries
d1 = {'A': 1, 'B': 2}
d2 = {'B': 3, 'C': 4}

# Combined using the union operator
combined = {**d1, **d2}
print(combined)  # Output: {'A': 1, 'B': 3, 'C': 4}

Here, the value of key B from d1 is replaced by the value from d2.

Using ChainMap to Retain Duplicate Keys

With ChainMap, you can combine dictionaries and maintain duplicate keys:

cm = ChainMap(d1, d2)
print(cm)  # Output: ChainMap({'A': 1, 'B': 2}, {'B': 3, 'C': 4})

When accessing a key, ChainMap always retrieves the value from the first dictionary:

print(cm['B'])  # Output: 2

Modifying the ChainMap

Any changes to the ChainMap affect the first dictionary only:

# Pop key 'B'
cm.pop('B')
print(cm)  # Output: ChainMap({'A': 1}, {'B': 3, 'C': 4})
print(d1)  # Output: {'A': 1}
print(d2)  # Output: {'B': 3, 'C': 4}

Adding a Temporary Dictionary

You can add an empty dictionary as the first mapping to make changes without affecting the original dictionaries:

cm = ChainMap({}, d1, d2)

# Add new keys
cm['Y'] = -1
cm['Z'] = 0
print(cm)  # Output: ChainMap({'Y': -1, 'Z': 0}, {'A': 1}, {'B': 3, 'C': 4})
print(d1)  # Output: {'A': 1}
print(d2)  # Output: {'B': 3, 'C': 4}

Creating ChainMap Using a Constructor

You can also create a ChainMap using the fromkeys method:

names = ['Bob', 'Sandra']
cm = ChainMap.fromkeys(names, None)
print(cm)  # Output: ChainMap({'Bob': None, 'Sandra': None})

Practical Application: Default Settings

A practical example of using ChainMap is combining default settings with user preferences:

default_settings = {'theme': 'light', 'language': 'English', 'notifications': True}
user_settings = {'theme': 'dark', 'notifications': False}

settings = ChainMap(user_settings, default_settings)
print(settings['theme'])         # Output: 'dark'
print(settings['language'])      # Output: 'English'
print(settings['notifications']) # Output: False

Here, ChainMap prioritizes user_settings while retaining fallback to default_settings.

Conclusion

ChainMap is a powerful tool for managing and combining dictionaries in Python without overwriting keys. Its applications range from handling settings to creating flexible data structures. By understanding and leveraging ChainMap, you can add an elegant solution to your Python programming toolkit.

Thank you for being a part of the community

Before you go:


메타데이터
post_id
f98d7ac5dfd0
slug
advanced-dictionary-operations-with-chainmap-f98d7ac5dfd0
url
https://python.plainenglish.io/advanced-dictionary-operations-with-chainmap-f98d7ac5dfd0
canonical_url
https://python.plainenglish.io/advanced-dictionary-operations-with-chainmap-f98d7ac5dfd0
author_url
https://medium.com/@naveenpandey2706
status
ok
fetched_at
2026-09-12 23:47:29