PYTHON
Concisely Merging Dictionaries in Python 3.9+ with the Union Operator
Explore the new `|` union operator for dictionaries in Python 3.9+ to efficiently merge multiple dictionaries into a single, new dictionary.
# Requires Python 3.9+
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'b': 5, 'e': 6} # Note 'b' is present in dict1 and dict3
# Merge dict1 and dict2
merged_dict_1_2 = dict1 | dict2
print(f"Merged dict1 and dict2: {merged_dict_1_2}")
# Merge dict1, dict2, and dict3.
# For duplicate keys, the value from the rightmost dictionary takes precedence.
merged_all = dict1 | dict2 | dict3
print(f"Merged all dictionaries: {merged_all}")
# Alternative for older Python versions (3.5+)
merged_old_version = {**dict1, **dict2, **dict3}
print(f"Merged (older version): {merged_old_version}")
# Expected output:
# Merged dict1 and dict2: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
# Merged all dictionaries: {'a': 1, 'b': 5, 'c': 3, 'd': 4, 'e': 6}
# Merged (older version): {'a': 1, 'b': 5, 'c': 3, 'd': 4, 'e': 6}
How it works: Python 3.9 introduced the `|` (union) operator for dictionaries, providing a concise way to merge two or more dictionaries into a new one. If keys overlap, the value from the rightmost dictionary in the operation takes precedence. This is a cleaner alternative to `**` unpacking for merging.