PYTHON
Merging Multiple Dictionaries Efficiently
Combine multiple Python dictionaries into a single dictionary using various methods, including the concise `|` operator for Python 3.9+ and other compatible approaches.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'a': 5, 'e': 6}
# Method 1: Using | operator (Python 3.9+)
merged_dict_39 = dict1 | dict2 | dict3
print(f"Merged (Python 3.9+): {merged_dict_39}")
# Method 2: Using ** operator (order matters for duplicate keys, last one wins)
merged_dict_star = {**dict1, **dict2, **dict3}
print(f"Merged (Star operator): {merged_dict_star}")
# Method 3: Using update() method (modifies dict1 or a new dict)
merged_dict_update = dict1.copy()
merged_dict_update.update(dict2)
merged_dict_update.update(dict3)
print(f"Merged (Update method): {merged_dict_update}")
How it works: This snippet demonstrates several ways to merge multiple Python dictionaries. The `|` operator (Python 3.9+) provides a clean, readable syntax. The `**` operator unpacks dictionaries into a new one, where values from later dictionaries for duplicate keys overwrite earlier ones. The `update()` method also merges dictionaries, but it modifies the dictionary it's called on or a copy of it.