Home > Article > Backend Development > How to combine two dictionaries in one expression
Now there are two Python dictionaries, write an expression to return the merger of the two dictionaries, how to achieve it?
The update() method here returns a null value instead of returning the merged object.
>>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print z None >>> x {'a': 1, 'b': 10, 'c': 11}
How can we finally save the value in z? Not x?
You can use the following method:
z = dict(x.items() + y.items())
Finally, the final result you want is saved in dictionary z, and the value of key b will be The values of the two dictionaries are overwritten.
>>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = dict(x.items() + y.items()) >>> z {'a': 1, 'c': 11, 'b': 10}
If you are using Python3, it is a little troublesome:
>>> z = dict(list(x.items()) + list(y.items())) >>> z {'a': 1, 'c': 11, 'b': 10}
You can also do this:
z = x.copy()
The above is the detailed content of How to combine two dictionaries in one expression. For more information, please follow other related articles on the PHP Chinese website!