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

How to combine two dictionaries in one expression

anonymity
anonymityOriginal
2019-05-24 14:51:072554browse

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}

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!

Statement:
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