我想避免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'
我怎样才能让它工作?
最佳答案
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())
在Python3上,
items
不像Python2那样返回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})
关于python - python3:具有“+”操作数的字典的和(联合)引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7096948/