PYTHON
Merging Dictionaries with | Operator (Python 3.9+)
Combine two or more Python dictionaries cleanly and concisely using the `|` operator (Python 3.9+) or the `**` unpacking operator for older versions, handling key conflicts.
dict1 = {'name': 'Alice', 'age': 30}
dict2 = {'city': 'New York', 'age': 31} # Note: 'age' is a conflicting key
dict3 = {'occupation': 'Engineer'}
# Using the | operator (Python 3.9+)
merged_dict_union = dict1 | dict2 | dict3
print(f"Merged with | operator: {merged_dict_union}")
# Note: For conflicting keys, the rightmost dictionary's value wins.
# For older Python versions (pre 3.9) or alternative syntax
merged_dict_unpacking = {**dict1, **dict2, **dict3}
print(f"Merged with ** unpacking: {merged_dict_unpacking}")
# Example with specific key precedence
settings_defaults = {'theme': 'dark', 'notifications': True, 'language': 'en'}
user_preferences = {'theme': 'light', 'language': 'fr'}
final_settings = settings_defaults | user_preferences
print(f"Final settings (user preferences override defaults): {final_settings}")
# Expected output:
# Merged with | operator: {'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
# Merged with ** unpacking: {'name': 'Alice', 'age': 31, 'city': 'New York', 'occupation': 'Engineer'}
# Final settings (user preferences override defaults): {'theme': 'light', 'notifications': True, 'language': 'fr'}
How it works: Python 3.9 introduced the `|` (union) operator for dictionaries, providing a concise way to merge them. When merging multiple dictionaries, if common keys exist, the value from the dictionary on the right-hand side takes precedence. For Python versions prior to 3.9, the `**` (dictionary unpacking) operator within a new dictionary literal achieves a similar merging effect, also giving precedence to values from dictionaries listed later. This allows for clean and explicit merging of configuration, data objects, or function arguments.