PYTHON
Merging Multiple Dictionaries in Python
Learn efficient ways to combine dictionaries in Python, covering both the `**` operator for Python 3.5+ and the `|` operator for Python 3.9+ to handle merges and key conflicts.
# Python 3.5+ (using unpacking operator)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged_dict_unpacking = {**dict1, **dict2}
print(f"Merged (unpacking): {merged_dict_unpacking}")
# Python 3.9+ (using union operator)
dict3 = {'x': 10, 'y': 20}
dict4 = {'y': 30, 'z': 40}
merged_dict_union = dict3 | dict4
print(f"Merged (union): {merged_dict_union}")
# Merging with new keys
dict5 = {'key1': 'value1'}
dict6 = {'key2': 'value2'}
merged_new_keys = {**dict5, **dict6}
print(f"Merged (new keys): {merged_new_keys}")
How it works: This snippet demonstrates two primary methods for merging dictionaries in Python. For Python 3.5 and later, the dictionary unpacking operator (`**`) allows you to merge dictionaries by unpacking their key-value pairs into a new dictionary. If keys overlap, the value from the dictionary unpacked last will prevail. For Python 3.9 and newer, the `|` (union) operator provides a more concise and readable syntax for dictionary merging, with the same conflict resolution behavior.