Home >Backend Development >Python Tutorial >How to Merge Two Dictionaries in Python with a Single Expression?
In Python 3.9.0 or greater, you can use the | operator:
z = x | y
In Python 3.5 or greater, you can use the double asterisk (**) operator:
z = {**x, **y}
In Python 2, or Python 3.4 or lower, you can define a function:
def merge_two_dicts(x, y): z = x.copy() z.update(y) return z
and then use the function:
z = merge_two_dicts(x, y)
Explanation:
When we say "merge two dictionaries", we mean creating a new dictionary (z) that contains all the key-value pairs from both x and y, with the values from y overwriting any duplicate keys in x.
The | operator has been added in Python 3.9 to specifically address this use case. It shallowly merges the dictionaries, giving precedence to the latter (i.e., y in our example).
The double asterisk operator (**) is another way to merge dictionaries. It expands the dictionaries as if they were passed as keyword arguments, and any duplicate keys are handled as expected (latter value takes precedence).
In Python 2, or 3.4 and earlier, we can still merge dictionaries by creating a new dictionary as a copy of x and then updating it with y. This ensures that x and y are not modified during the process.
The above is the detailed content of How to Merge Two Dictionaries in Python with a Single Expression?. For more information, please follow other related articles on the PHP Chinese website!