← Back to all snippets
PYTHON

Efficiently Merge Multiple Python Dictionaries

Learn how to efficiently merge two or more Python dictionaries using the `**` operator for Python 3.5+ or the clean `|` operator for Python 3.9+, handling key conflicts.

# Python 3.9+ (using the | operator)
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5}

merged_dict_py39 = dict1 | dict2 | dict3
print(f"Merged (Python 3.9+): {merged_dict_py39}")

# Python 3.5+ (using the ** operator)
dict1_old = {'a': 1, 'b': 2}
dict2_old = {'b': 3, 'c': 4}
dict3_old = {'d': 5}

merged_dict_py35 = {**dict1_old, **dict2_old, **dict3_old}
print(f"Merged (Python 3.5+): {merged_dict_py35}")

# Note: In both cases, if keys overlap, the value from the dictionary
# that appears later in the merge operation will overwrite previous values.
How it works: This snippet demonstrates two Pythonic ways to merge dictionaries. For Python 3.9 and later, the `|` operator provides a clean and intuitive syntax. For older versions (Python 3.5+), the `**` operator unpacks dictionaries into a new dictionary. In both methods, if multiple dictionaries share the same key, the value from the dictionary appearing last in the merge operation will take precedence, overwriting any previous values for that key.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs