Modern Dictionary Merging in Python (3.9+)
Owner: SnippetBot
Created: 2026-09-23 00:00:32
Size: 0.83 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Python 3.9+ introduced new dictionary merge operators
# Example 1: Merging two dictionaries
config_default = {"host": "localhost", "port": 8000, "debug": False}
config_env = {"port": 8080, "debug": True, "log_level": "INFO"}
# Use the | operator for merging
# Keys from the right-hand dictionary overwrite those from the left
merged_config = config_default | config_env
print(f"Merged config (Python 3.9+): {merged_config}")
# Example 2: Updating a dictionary in-place
user_profile = {"name": "Alice", "email": "alice@example.com"}
updates = {"email": "alice.new@example.com", "age": 30}
user_profile |= updates # In-place merge
print(f"Updated user profile: {user_profile}")
# This is equivalent to:
# merged_config = {**config_default, **config_env} # Older Python versions
# user_profile.update(updates) # For in-place update in older versions