PYTHON
Merging Python Dictionaries with Update Operator and Unpacking
Explore Pythonic ways to merge dictionaries, handling duplicate keys using the dictionary `update()` method and dictionary unpacking for Python 3.5+.
# Original dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5}
# Method 1: Using the update() method
# Modifies dict1 in place. Keys from dict2 overwrite keys in dict1.
merged_dict_update = dict1.copy() # Create a copy to avoid modifying original dict1
merged_dict_update.update(dict2)
print(f"Merged with update(): {merged_dict_update}") # Output: Merged with update(): {'a': 1, 'b': 3, 'c': 4}
# Method 2: Using dictionary unpacking (Python 3.5+)
# Creates a new dictionary. Later dictionaries' keys overwrite earlier ones.
merged_dict_unpack = {**dict1, **dict2, **dict3}
print(f"Merged with unpacking: {merged_dict_unpack}") # Output: Merged with unpacking: {'a': 1, 'b': 3, 'c': 4, 'd': 5}
# Method 3: Using the union operator (Python 3.9+)
# Creates a new dictionary. Later dictionaries' keys overwrite earlier ones.
merged_dict_union = dict1 | dict2 | dict3
print(f"Merged with union operator: {merged_dict_union}") # Output: Merged with union operator: {'a': 1, 'b': 3, 'c': 4, 'd': 5}
How it works: Merging dictionaries is a common task. Python offers several elegant ways. The `update()` method merges a dictionary into another, overwriting existing keys. Dictionary unpacking `{**d1, **d2}` creates a new dictionary from the contents of multiple dictionaries, with keys from later dictionaries overriding earlier ones. For Python 3.9 and later, the `|` (union) operator provides an even more concise syntax for merging dictionaries, also creating a new dictionary and resolving key conflicts by favoring the rightmost dictionary.