PYTHON

Merging Dictionaries with Python's Union Operator (Python 3.9+)

Discover the concise new `|` operator introduced in Python 3.9 for merging dictionaries, providing an elegant and efficient way to combine dictionary data in your web applications and configurations.

# Initial dictionaries
dict1 = {"name": "Alice", "age": 30}
dict2 = {"city": "New York", "occupation": "Engineer"}
dict3 = {"age": 32, "email": "[email protected]"}

# Using the | operator to merge two dictionaries (Python 3.9+)
merged_dict_simple = dict1 | dict2
print(f"Simple merge: {merged_dict_simple}")

# Merging with overlapping keys (right-hand dictionary wins)
merged_dict_overlap = dict1 | dict3
print(f"Merge with overlap (dict3 wins): {merged_dict_overlap}")

# Using the |= operator for in-place merge (Python 3.9+)
config = {"host": "localhost", "port": 8000}
defaults = {"port": 5000, "debug": True}
config |= defaults # updates config with defaults, defaults['port'] overrides
print(f"In-place merge (config |= defaults): {config}")
How it works: Python 3.9 introduced the `|` (union) and `|=` (in-place union) operators for dictionaries, providing a cleaner syntax for merging. When merging dictionaries, if there are overlapping keys, the value from the right-hand side dictionary takes precedence. The `|` operator creates a new dictionary, while `|=` modifies the dictionary on its left-hand side. This significantly simplifies common tasks like combining configuration settings or request data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs