PYTHON
Efficiently Merge Dictionaries (Python 3.9+)
Discover the clean and concise way to merge multiple dictionaries using Python's dictionary union operators (| and |=), introduced in Python 3.9, ideal for configurations and data updates.
# Base configuration
config_defaults = {"host": "localhost", "port": 8000, "debug": False}
# User-specific settings (e.g., from environment variables or a settings file)
user_settings = {"port": 8080, "debug": True, "log_level": "INFO"}
# Request-specific overrides
request_params = {"debug": False, "timeout": 30}
# --- Merging Dictionaries ---
# 1. Create a new dictionary by merging (using the `|` operator, Python 3.9+)
# Keys in later dictionaries override those in earlier ones.
merged_config = config_defaults | user_settings | request_params
print(f"Merged config (new dict): {merged_config}")
# Expected: {'host': 'localhost', 'port': 8080, 'debug': False, 'log_level': 'INFO', 'timeout': 30}
# 2. Update an existing dictionary in-place (using the `|=` operator, Python 3.9+)
# This modifies `config_defaults` directly.
config_defaults |= user_settings
print(f"Updated config_defaults (in-place): {config_defaults}")
# Expected: {'host': 'localhost', 'port': 8080, 'debug': True, 'log_level': 'INFO'}
# For Python < 3.9, or explicit update:
# dict.update() method:
legacy_merged = config_defaults.copy()
legacy_merged.update(user_settings)
legacy_merged.update(request_params)
print(f"Merged config (legacy update): {legacy_merged}")
How it works: Python 3.9 introduced dictionary union operators (`|` for new dictionary creation and `|=` for in-place update), offering a more readable and Pythonic way to merge dictionaries compared to older methods like `dict.update()` or unpacking with `**`. When merging, if keys overlap, values from the right-hand dictionary take precedence. These operators are incredibly useful for combining configuration settings, request parameters, or default values with user-provided overrides in web applications.