PYTHON
Merge Python Dictionaries
Discover how to efficiently merge two or more Python dictionaries, handling overlapping keys gracefully, using modern Python 3.9+ syntax and older unpacking methods.
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5, 'a': 6}
# Python 3.9+ using | operator (merge, dict2 overrides dict1)
merged_dict_3_9 = dict1 | dict2
print(f"Python 3.9+ merge (dict1 | dict2): {merged_dict_3_9}")
# Older Python versions or alternative using ** unpacking (dict2 overrides dict1)
merged_dict_unpack = {**dict1, **dict2, **dict3}
print(f"Unpacking merge (**dict1, **dict2, **dict3): {merged_dict_unpack}")
# Create a new dictionary from multiple sources (last dict wins for duplicate keys)
final_settings = {'timeout': 30, 'retries': 3}
user_settings = {'retries': 5, 'cache_enabled': True}
default_settings = {'timeout': 60, 'log_level': 'INFO'}
combined_settings = {**default_settings, **final_settings, **user_settings}
print(f"Combined settings (user overrides final, final overrides default): {combined_settings}")
How it works: Python offers elegant ways to merge dictionaries. For Python 3.9 and later, the `|` operator provides a concise syntax, with the right-hand dictionary's values overriding those from the left if keys overlap. For older versions or multi-dictionary merges, the `**` unpacking operator creates a new dictionary from the key-value pairs of the input dictionaries, where later dictionaries in the unpacking sequence override earlier ones for duplicate keys.