PYTHON
Modern Dictionary Merging with Python 3.9+ `|` Operator
Discover the concise and readable way to merge or update dictionaries in Python 3.9 and later using the new `|` operator, simplifying configuration and data handling.
# Default configuration for a web application
default_config = {
"DEBUG": False,
"HOST": "127.0.0.1",
"PORT": 5000,
"DATABASE_URL": "sqlite:///app.db"
}
# Environment-specific configuration (e.g., production overrides)
production_config = {
"DEBUG": False,
"HOST": "0.0.0.0",
"DATABASE_URL": "postgresql://user:pass@host:5432/prod_db",
"SECRET_KEY": "super_secret_key"
}
# Merge default_config with production_config.
# Values from the right-hand dictionary (production_config) take precedence.
final_config = default_config | production_config
print(f"Merged Configuration: {final_config}")
# Another example: Merging request headers
base_headers = {"User-Agent": "WebApp/1.0", "Accept": "application/json"}
auth_header = {"Authorization": "Bearer abc123def456"}
request_headers = base_headers | auth_header
print(f"Request Headers: {request_headers}")
# For earlier Python versions (<3.9), use:
# merged_dict = {**dict1, **dict2}
How it works: This snippet showcases the modern `|` operator (union operator) for merging dictionaries, introduced in Python 3.9. It provides a clean and idiomatic way to combine dictionaries, with values from the right-hand operand overriding those in the left-hand operand. This is extremely useful in web development for managing configuration settings, combining request headers, or merging data payloads, offering a more readable alternative to `dict.update()` or `**` unpacking for shallow merges.