我想避免使用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'
我怎样才能让它发挥作用?
答案 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)