python3:字典使用"+"运算符求和(并集)时引发异常

2 投票
2 回答
3337 浏览
提问于 2025-04-16 23:48

我想避免使用update()这个方法,我听说可以用“+”符号把两个字典合并成一个新的字典,但在我的命令行里出现了这样的情况:

>>> {'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 个回答

7

从Python 3.5开始,这种写法是:

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

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

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,而是返回一个字典视图。如果你想使用+,你需要把它们转换成list

其实你可以直接使用update,不管有没有copy,这样更好:

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

撰写回答