PYTHON
Combine Multiple Dictionaries with ChainMap for Flexible Lookups
Explore `collections.ChainMap` in Python to link several dictionaries into a single, updateable view. Ideal for managing scopes, configurations, or hierarchical data lookups efficiently.
from collections import ChainMap
# Define multiple dictionaries
config_defaults = {'theme': 'dark', 'font_size': 12, 'debug': False}
user_settings = {'font_size': 14, 'language': 'en'}
session_overrides = {'debug': True}
# Create a ChainMap
# Lookups proceed from left to right (session_overrides first, then user_settings, then config_defaults)
combined_config = ChainMap(session_overrides, user_settings, config_defaults)
print(f"Combined configuration (ChainMap): {combined_config}")
# Accessing values - higher priority (leftmost) dict wins
print(f"Theme: {combined_config['theme']}") # From config_defaults
print(f"Font Size: {combined_config['font_size']}") # From user_settings
print(f"Debug: {combined_config['debug']}") # From session_overrides
print(f"Language: {combined_config['language']}") # From user_settings
# Adding a new dictionary to the chain (creates a new ChainMap)
new_override = {'cache_enabled': True}
updated_config = combined_config.new_child(new_override)
print(f"
Updated configuration with new child: {updated_config}")
print(f"Cache Enabled: {updated_config['cache_enabled']}")
# Modifications to the ChainMap affect the first dictionary in the chain
# (or the dictionary specified if using indexing for updates)
combined_config['language'] = 'fr'
print(f"User settings after ChainMap modification: {user_settings}")
print(f"Language from combined_config after modification: {combined_config['language']}")
How it works: `collections.ChainMap` is a class for quickly linking a number of mappings (like dictionaries) together to create a single, updateable view. It's particularly useful for implementing lexical scopes, where data is looked up in a chain of contexts, or for managing configuration settings from multiple sources with different priorities. Lookups search the underlying mappings from left to right until a key is found. Writes, however, only affect the first mapping in the chain, enabling a 'shadowing' effect without modifying the source dictionaries.