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

时间:2011-08-17 17:28:24

标签: python python-3.x dictionary 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'

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

2 个答案:

答案 0 :(得分:8)

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

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

在Python 3上,items不会像Python 2中那样返回list,而是dict view。如果您要使用+,则需要将其转换为list s。

使用update时,最好不要使用copy

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

答案 1 :(得分:7)

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

{**dict1, **dict2, ...}

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