PYTHON
Efficiently Merging Python Dictionaries
Learn how to efficiently merge Python dictionaries, combining their key-value pairs using various methods like `update()` and the new union operators (`|`, `|=`) for flexible data handling.
# Python 3.9+ for `|` and `|=` operators
def merge_dictionaries(dict1, dict2):
# Method 1: Non-destructive merge (creates a new dictionary)
# Using ** unpacking (works in older Python versions)
merged_dict_unpacking = {**dict1, **dict2}
print(f"Merged (unpacking): {merged_dict_unpacking}")
# Using dictionary union operator (Python 3.9+)
merged_dict_union = dict1 | dict2
print(f"Merged (union operator): {merged_dict_union}")
# Method 2: Destructive merge (modifies dict1 in-place)
dict1_copy = dict1.copy() # Work on a copy to show original dict1 state
dict1_copy.update(dict2)
print(f"Merged (update in-place): {dict1_copy}")
# Example Usage
data1 = {'name': 'Alice', 'age': 30}
data2 = {'city': 'New York', 'age': 31, 'occupation': 'Engineer'}
data3 = {'country': 'USA'}
merge_dictionaries(data1, data2)
merge_dictionaries(data1, data3)
# Example with the union assignment operator (Python 3.9+)
settings = {'debug': False, 'env': 'dev'}
prod_settings = {'debug': True, 'env': 'prod', 'db_host': 'prod-db'}
settings |= prod_settings # Modifies 'settings' in-place
print(f"Settings after union assignment: {settings}")
How it works: This snippet demonstrates several methods for merging Python dictionaries. The `**` unpacking operator and the `|` union operator (Python 3.9+) create a new dictionary by combining the key-value pairs of the input dictionaries, with the rightmost dictionary's values overriding duplicates. The `update()` method performs an in-place merge, modifying the dictionary it's called on. The `|=` union assignment operator (Python 3.9+) also modifies the dictionary in-place. These methods are crucial for combining configurations, API parameters, or user input data efficiently.