Merging and Updating Dictionaries with Modern Python Syntax
Owner: SnippetBot
Created: 2026-10-07 00:00:30
Size: 1.28 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
dict1 = {"name": "Alice", "age": 30}
dict2 = {"city": "New York", "occupation": "Engineer"}
dict3 = {"age": 31, "email": "alice@example.com"}
# 1. Merging with the dictionary unpacking operator (**) (Python 3.5+)
# This creates a new dictionary. If keys overlap, the latter dictionary's value wins.
merged_dict_unpacking = {**dict1, **dict2, **dict3}
print(f"Merged with unpacking (**): {merged_dict_unpacking}")
# 2. Merging with the dictionary union operator (|) (Python 3.9+)
# This also creates a new dictionary. Right-hand operand wins on conflict.
merged_dict_union = dict1 | dict2 | dict3
print(f"Merged with union operator (|): {merged_dict_union}")
# 3. Updating an existing dictionary (in-place modification)
# Use .update() method
settings = {"theme": "dark", "notifications": True}
user_preferences = {"notifications": False, "language": "en"}
print(f"Original settings: {settings}")
settings.update(user_preferences)
print(f"Updated settings (in-place): {settings}")
# Example: Combining default and user-provided configuration
default_config = {"host": "localhost", "port": 8000, "debug": False}
user_config = {"port": 8080, "debug": True, "log_level": "INFO"}
final_config = {**default_config, **user_config} # user_config overrides default_config
print(f"Final configuration: {final_config}")