PYTHON

Combine Multiple Dictionaries with collections.ChainMap

Learn how to use Python's collections.ChainMap to create a single, logical view of multiple dictionaries, useful for configuration management.

from collections import ChainMap

# Define several dictionaries
default_settings = {'debug': False, 'logging_level': 'INFO', 'port': 8000}
user_settings = {'debug': True, 'port': 8080}
env_settings = {'logging_level': 'DEBUG'} # Could be loaded from environment variables

# Create a ChainMap to combine them, with lookup preference from left to right
# user_settings overrides default_settings, env_settings overrides user_settings
config = ChainMap(env_settings, user_settings, default_settings)

print(f"All settings: {config}")
print(f"Debug setting: {config['debug']}") # Looks in env_settings, then user_settings, then default_settings
print(f"Logging level: {config['logging_level']}")
print(f"Port: {config['port']}")
print(f"Non-existent key (returns KeyError):")
try:
    print(config['database_url'])
except KeyError as e:
    print(f"Error: {e}")

# Modifying the ChainMap adds/updates the first dictionary in the chain
config['new_param'] = 'test_value'
print(f"Modified env_settings: {env_settings}")
print(f"Updated config: {config}")

# Accessing underlying maps
print(f"Underlying maps: {config.maps}")
How it works: This snippet demonstrates `collections.ChainMap`, a powerful data structure for combining multiple dictionaries into a single view. When accessing a key, `ChainMap` searches through the dictionaries in the order they were provided, returning the first value found. This is particularly useful for managing hierarchical configurations, where settings from different sources (e.g., defaults, user prefs, environment variables) override each other.

Need help integrating this into your project?

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

Hire DigitalCodeLabs