PYTHON

Merge Multiple Dictionaries Concisely (Python 3.9+)

Discover the modern and Pythonic way to merge several dictionaries into a single dictionary using the `|` union operator introduced in Python 3.9, with clear examples.

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
dict3 = {'e': 5, 'a': 6} # Note: 'a' is duplicated, last one wins

# Merge two dictionaries using the | operator (Python 3.9+)
merged_dict_two = dict1 | dict2
print(f"Merged two dictionaries: {merged_dict_two}")
# Expected: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Merge multiple dictionaries (Python 3.9+)
merged_dict_multiple = dict1 | dict2 | dict3
print(f"Merged multiple dictionaries: {merged_dict_multiple}")
# Expected: {'a': 6, 'b': 2, 'c': 3, 'd': 4, 'e': 5} (last 'a' value wins)

# For older Python versions (pre-3.9)
merged_dict_older = {**dict1, **dict2, **dict3}
print(f"Merged (older Python syntax): {merged_dict_older}")
# Expected: {'a': 6, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
How it works: This snippet demonstrates the clean and readable way to merge dictionaries in Python. For Python 3.9 and later, the `|` (union) operator provides a direct syntax for combining dictionaries. When keys overlap, the value from the rightmost dictionary in the expression takes precedence. For older Python versions, the `**` operator (dictionary unpacking) within a new dictionary literal achieves the same result, also with the rightmost value winning on key conflicts.

Need help integrating this into your project?

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

Hire DigitalCodeLabs