PYTHON
Modern Pythonic Ways to Merge Dictionaries
Explore efficient and concise methods to merge two or more dictionaries in Python, covering the `|` operator (Python 3.9+) and `**` unpacking for various scenarios.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'b': 5, 'e': 6}
# Method 1: Using the dictionary union operator (Python 3.9+)
# Keys from later dictionaries overwrite keys from earlier ones.
merged_dict_union = dict1 | dict2 | dict3
print(f"Merged with union operator: {merged_dict_union}")
# Method 2: Using the ** unpacking operator (Older Python versions or for specific control)
# Note: Later dictionaries' values for duplicate keys will overwrite earlier ones.
merged_dict_unpacking = {**dict1, **dict2, **dict3}
print(f"Merged with unpacking operator: {merged_dict_unpacking}")
How it works: Merging dictionaries is a common task. Python 3.9+ introduced the `|` (union) operator for dictionaries, providing a clean and readable way to combine them. For older Python versions, or when more fine-grained control is needed, the `**` unpacking operator within a new dictionary literal achieves similar results. Both methods handle duplicate keys by allowing the values from later dictionaries to override earlier ones.