PYTHON

Merge Multiple Dictionaries into One

Combine several Python dictionaries into a single dictionary using the union operator (|) for Python 3.9+ or the `**` unpacking operator for older versions, ideal for consolidating configurations or data.

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5}

# Python 3.9+ (Recommended)
merged_dict_39 = dict1 | dict2 | dict3

# Python < 3.9 (Also works in 3.9+)
merged_dict_old = {**dict1, **dict2, **dict3}

# Result for both:
# {'a': 1, 'b': 3, 'c': 4, 'd': 5}
How it works: This code demonstrates two ways to merge multiple dictionaries. For Python 3.9 and newer, the `|` (union) operator provides a clean and readable way to combine dictionaries. For older Python versions, or as an alternative, the `**` unpacking operator can be used inside a new dictionary literal. In both methods, if keys conflict, the value from the rightmost (or latest) dictionary takes precedence.

Need help integrating this into your project?

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

Hire DigitalCodeLabs