Home > Backend Development > Python Tutorial > How to combine two dictionaries in one expression

How to combine two dictionaries in one expression

anonymity
Release: 2019-05-25 09:49:13
Original
2541 people have browsed it

Now there are two Python dictionaries, write an expression to return the merger of the two dictionaries, how to achieve it?

How to combine two dictionaries in one expression

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}
Copy after login

How can we finally save the value in z? Not x?

You can use the following method:

z = dict(x.items() + y.items())
Copy after login

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}
Copy after login

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}
Copy after login

You can also do this:

z = x.copy()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template