0
0
PythonHow-ToBeginner · 3 min read

How to Use ChainMap in Python: Simple Guide with Examples

Use collections.ChainMap to group multiple dictionaries into a single view that searches each dictionary in order. It allows easy lookup and update without merging dictionaries manually.
📐

Syntax

The basic syntax to create a ChainMap is ChainMap(dict1, dict2, ...). Each argument is a dictionary or a mapping. The ChainMap searches keys in the order the dictionaries are given.

You can access values like a normal dictionary, and updates affect the first dictionary in the chain.

python
from collections import ChainMap

# Create ChainMap with two dictionaries
chain = ChainMap({'a': 1, 'b': 2}, {'b': 3, 'c': 4})
💻

Example

This example shows how ChainMap combines two dictionaries. Lookup checks the first dictionary first, then the second. Updates change the first dictionary only.

python
from collections import ChainMap

# Two dictionaries
dict1 = {'apple': 1, 'banana': 2}
dict2 = {'banana': 3, 'cherry': 4}

# Create ChainMap
combined = ChainMap(dict1, dict2)

# Access values
print(combined['apple'])   # From dict1
print(combined['banana'])  # From dict1, not dict2
print(combined['cherry'])  # From dict2

# Update value
combined['banana'] = 10
print(dict1['banana'])     # Updated in dict1

# Add new key
combined['date'] = 5
print(dict1['date'])       # Added to dict1
Output
1 2 4 10 5
⚠️

Common Pitfalls

One common mistake is expecting updates to affect all dictionaries. Actually, changes only affect the first dictionary in the ChainMap. Also, deleting keys only works on the first dictionary.

Another pitfall is modifying the ChainMap without understanding the order of dictionaries, which can cause unexpected lookups.

python
from collections import ChainMap

# Setup
first = {'x': 1}
second = {'x': 2}
cm = ChainMap(first, second)

# Wrong: expecting update to change second dict
cm['x'] = 10
print(second['x'])  # Still 2, not changed

# Correct: update affects first dict only
print(first['x'])   # Now 10
Output
2 10
📊

Quick Reference

OperationDescription
ChainMap(dict1, dict2, ...)Combine multiple dictionaries into one view
cm[key]Look up key searching each dictionary in order
cm[key] = valueUpdate or add key in the first dictionary
del cm[key]Delete key from the first dictionary
cm.mapsList of dictionaries in the ChainMap

Key Takeaways

ChainMap groups multiple dictionaries for combined key lookup without merging.
Lookups check dictionaries in the order they are passed to ChainMap.
Updates and deletions affect only the first dictionary in the ChainMap.
Use ChainMap to manage layered configurations or scopes easily.
Access the underlying dictionaries with the .maps attribute.