How to Use ChainMap in Python: Simple Guide with Examples
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.
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.
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
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.
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
Quick Reference
| Operation | Description |
|---|---|
| ChainMap(dict1, dict2, ...) | Combine multiple dictionaries into one view |
| cm[key] | Look up key searching each dictionary in order |
| cm[key] = value | Update or add key in the first dictionary |
| del cm[key] | Delete key from the first dictionary |
| cm.maps | List of dictionaries in the ChainMap |