PYTHON

Layering Dictionaries with collections.ChainMap

Learn to combine multiple dictionaries into a single, searchable unit using Python's ChainMap, ideal for managing layered configurations or contextual scopes effectively.

from collections import ChainMap

# Define multiple dictionaries representing layers of configuration
defaults = {'theme': 'dark', 'log_level': 'INFO', 'timeout': 30}
user_config = {'log_level': 'DEBUG', 'timeout': 60, 'language': 'en'}
cli_args = {'timeout': 120, 'verbose': True}

# Combine them into a ChainMap. Search order: cli_args -> user_config -> defaults
config = ChainMap(cli_args, user_config, defaults)

print(f"Effective config: {config}")
print(f"Theme: {config['theme']}") # From defaults
print(f"Log Level: {config['log_level']}") # From user_config
print(f"Timeout: {config['timeout']}") # From cli_args (highest precedence)
print(f"Verbose: {config['verbose']}")

# Modifying a value affects the first dictionary it's found in (or the first map if new)
config['timeout'] = 150
print(f"Modified Timeout (in cli_args): {config['timeout']}")
print(f"cli_args after modification: {cli_args}")

# Add a new map as the highest priority
runtime_overrides = {'debug_mode': True}
config = config.new_child(runtime_overrides)
print(f"
Config with new runtime overrides: {config}")
print(f"Debug Mode: {config['debug_mode']}")
How it works: `collections.ChainMap` provides an elegant way to link multiple dictionaries together, creating a single, updatable view. When a key is looked up, `ChainMap` searches through the underlying dictionaries in the order they were provided, returning the first value found. Writes, however, only affect the first dictionary in the chain. This is highly useful for managing layered configurations, scopes, or environments where values from a higher-priority dictionary should override those in lower-priority ones.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs