Introduction
ChainMap groups multiple dictionaries into a single view, searching them in order.
Basic ChainMap
from collections import ChainMap
# Create chain from dicts
defaults = {"theme": "light", "language": "en"}
user_prefs = {"language": "fr", "notifications": True}
combined = ChainMap(user_prefs, defaults)
print(combined["theme"]) # light (from defaults)
print(combined["language"]) # fr (from user_prefs)
print(combined["notifications"]) # True
Modifications
combined = ChainMap(user_prefs, defaults)
# Changes affect first map only
combined["theme"] = "dark"
print(user_prefs) # {'language': 'fr', 'theme': 'dark'}
# Add to first map
combined["new_key"] = "value"
Use Cases
from collections import ChainMap
# Command-line arguments with defaults
defaults = {"debug": False, "port": 8000}
args = {"port": 3000}
config = ChainMap(args, defaults)
# Variable scoping
local_vars = {"x": 1}
global_vars = {"y": 2}
all_vars = ChainMap(local_vars, global_vars)
Practice Problems
- Create search path with ChainMap
- Implement priority config loading
- Merge multiple dictionaries with priority
- Update ChainMap efficiently
- Use ChainMap for namespace lookup