python 3 : sum (union) of dictionaries with "+" operand raises exception

标签 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'

我怎样才能让它工作?

最佳答案

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

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

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

关于 python 3 : sum (union) of dictionaries with "+" operand raises exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7096948/

相关文章:

python - 为什么对 dict2 中的嵌套字典的更改会影响 dict1?

python - 为什么我的埃拉托色尼筛法这么慢?

python - Python中的循环导入依赖

python - aiogevent 事件循环 "fails"跟踪greenlets

python - 字典可以用作 matplotlib.pyplot 的完整输入吗?

python - 通过内部字典中多个键的值过滤Python字典

python - 如何清除 PyTorch 中的 CUDA 内存

Python 文档测试 : Skip entire block?

python - 在最后一次迭代的 for 循环之外打印一些内容

python - 将 Python 的多处理模块与 cvxopt 包一起使用