PYTHON
Merge Multiple Python Dictionaries
Learn different Python methods to shallow merge several dictionaries into a single one, handling potential key conflicts gracefully for consolidated data.
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'a': 5, 'e': 6} # Note 'a' key conflict
# Method 1: Using ** (unpacking operator) - Python 3.5+
# Keys from later dictionaries overwrite earlier ones
merged_dict_unpacking = {**dict1, **dict2, **dict3}
print(f"Merged with **: {merged_dict_unpacking}")
# Method 2: Using the | operator - Python 3.9+
merged_dict_union = dict1 | dict2 | dict3
print(f"Merged with |: {merged_dict_union}")
# Method 3: Using .update() method (modifies the first dict)
merged_dict_update = dict1.copy() # Start with a copy to avoid modifying original
merged_dict_update.update(dict2)
merged_dict_update.update(dict3)
print(f"Merged with .update(): {merged_dict_update}")
How it works: This code snippet illustrates three common methods for merging multiple dictionaries in Python. The `**` (unpacking) operator and the `|` (union) operator (Python 3.9+) provide concise ways to create a new merged dictionary. When duplicate keys exist, the value from the rightmost (later) dictionary takes precedence. The `.update()` method modifies an existing dictionary in place, so a copy is often made first to preserve the original dictionaries.