python3:带有"+"操作数的字典的sum(union)引发异常

etu*_*rdu 2 python dictionary python-3.x dictview

我想避免使用update()方法,并且我读到可以使用"+"操作数将两个字典合并到第三个字典中,但在我的shell中发生的是:

>>> {'a':1, 'b':2}.items() + {'x':98, 'y':99}.items()
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    {'a':1, 'b':2}.items() + {'x':98, 'y':99}.items()
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
>>> {'a':1, 'b':2} + {'x':98, 'y':99}
Traceback (most recent call last):
  File "<pyshell#85>", line 1, in <module>
    {'a':1, 'b':2} + {'x':98, 'y':99}
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
Run Code Online (Sandbox Code Playgroud)

我怎样才能让它发挥作用?

agf*_*agf 8

dicts = {'a':1, 'b':2}, {'x':98, 'y':99}
new_dict = dict(sum(list(d.items()) for d in dicts, []))
Run Code Online (Sandbox Code Playgroud)

要么

new_dict = list({'a':1, 'b':2}.items()) + list({'x':98, 'y':99}.items())
Run Code Online (Sandbox Code Playgroud)

在Python 3上,items不会list在Python 2中返回类似内容,而是返回dict视图.如果要使用+,则需要将它们转换为lists.

update无论是否使用,您最好使用copy:

# doesn't change the original dicts
new_dict = {'a':1, 'b':2}.copy()
new_dict.update({'x':98, 'y':99})
Run Code Online (Sandbox Code Playgroud)


Dim*_*nek 7

从Python 3.5开始,这个成语是:

{**dict1, **dict2, ...}
Run Code Online (Sandbox Code Playgroud)

https://www.python.org/dev/peps/pep-0448/