PYTHON
Creating a Combined Dictionary View with `collections.ChainMap`
Efficiently combine multiple dictionaries into a single, logical view for lookups and updates using `collections.ChainMap` without creating copies.
from collections import ChainMap
def create_config_chain(default_config, user_config, env_config):
# Order matters: env_config overrides user_config, which overrides default_config
return ChainMap(env_config, user_config, default_config)
default_settings = {'debug': False, 'port': 8000, 'host': 'localhost'}
user_settings = {'port': 8080, 'debug': True}
environment_settings = {'host': '0.0.0.0'}
config = create_config_chain(default_settings, user_settings, environment_settings)
print(f"Debug setting: {config['debug']}") # True (from user_settings)
print(f"Port setting: {config['port']}") # 8080 (from user_settings)
print(f"Host setting: {config['host']}") # 0.0.0.0 (from environment_settings)
print(f"All keys: {list(config.keys())}")
# Updates write to the first dictionary in the chain
config['port'] = 9000
print(f"Environment settings after update: {environment_settings}") # {'host': '0.0.0.0', 'port': 9000}
How it works: `collections.ChainMap` offers a way to combine multiple dictionaries into a single logical mapping for lookups and updates. It searches the dictionaries in the order they are provided, returning the first value found for a given key. New entries or updates are always written to the first dictionary in the chain. This is highly useful for managing configuration settings where you want to prioritize overrides from different sources (e.g., environment variables over user settings over default settings) without explicitly merging dictionaries.