PYTHON
Merging Dictionaries with `**` and `|` Operators
Learn modern Python techniques for merging multiple dictionaries efficiently using the `**` operator for unpacking and the new `|` union operator (Python 3.9+).
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'a': 5, 'e': 6}
# Method 1: Using ** (Python 3.5+)
merged_dict_star = {**dict1, **dict2, **dict3}
print(f"Merged with **: {merged_dict_star}")
# Output: {'a': 5, 'b': 2, 'c': 3, 'd': 4, 'e': 6} - dict3's 'a' overwrites dict1's 'a'
# Method 2: Using | (Python 3.9+)
merged_dict_pipe = dict1 | dict2 | dict3
print(f"Merged with |: {merged_dict_pipe}")
# Output: {'a': 5, 'b': 2, 'c': 3, 'd': 4, 'e': 6} - dict3's 'a' overwrites dict1's 'a'
# Updating a dictionary in-place (old way using .update(), also common)
dict_to_update = {'x': 10}
dict_to_update.update(dict1)
print(f"Updated in-place: {dict_to_update}")
How it works: This snippet showcases efficient ways to merge dictionaries in Python. The `**` operator (unpacking operator) creates a new dictionary by expanding other dictionaries, with keys from later dictionaries overwriting earlier ones. Python 3.9+ introduced the `|` (union) operator, providing a more concise and readable syntax for the same merging behavior. For in-place updates, the `.update()` method remains a valid and common choice.