python - 类型错误 : unsupported operand type(s) for +: 'dict_items' and 'dict_items'

标签 python python-3.x

我试着像这样总结两个字典:

my_new_dict = dict(my_existing_dict.items() + my_new_dict.items())

但收到错误

TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'

我做错了什么?

最佳答案

从 Python 3.9(尤其是 PEP 584)开始,dicts 像集合一样获得联合(|)和更新(|=)操作,因此成为“一种真正的方式”来实现您正在寻找的东西。

d1 | d2

该 PEP 列出了早期 Python 版本中可用的其他选项,这些选项都有其缺点。如果您达到 PEP 448 (Python 3.5),我建议使用:

{**d1, **d2}

这是将两个字典解包成一个新字典,从而形成一个联合。

一个问题是你想要的行为是模棱两可的——字典不能有重复的键,所以如果两者都包含相同的键,你就不清楚你想要发生什么。规范明确说明了使用此方法时会发生什么:

In dictionaries, later values will always override earlier ones

如果你想要相反的行为,你可以简单地交换字典中文字的顺序。

您的方法不起作用,因为 dictionary views are set-like ,所以他们没有实现加法。

您可能想要的是 union : d1.items() | d2.items(),它将为您提供一组 (key, value) 元组。如果您随后将其传递给 dict() 并且有重复项,则“最后一个”值将是使用的值,但是集合(与 View 本身不同)是无序的,因此无法保证哪个项目将在组合集中以“第一”结束,这意味着哪个“获胜”将是任意的。

所以,简而言之,只要订单/重复选择不重要:

dict(d1.items() | d2.items())

在 Python 2 中,dict.items() 只返回一个 list,您的方法将在其中起作用。

关于python - 类型错误 : unsupported operand type(s) for +: 'dict_items' and 'dict_items' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13361510/

相关文章:

python - 标准输入非交互式时如何清除python中的标准输入缓冲区

python - OpenCV for ARM (Beagleboard) 使用 YUYV 而不是 JPEG 压缩?

python - 如何用python中的列表替换json的某些键和值

Python 3 和 Pandas - 在 DataFrame 中创建新行但为空 DataFrame

python - FCM API 'Bad request 400' 错误

python - 'str' 对象在 Python3 中没有属性 'decode'

python - 在 Python 中比较黄金标准 csv 文件和提取值 csv 文件

由于缩进而导致 Python 打印错误

python - 使用 TensorFlow 进行图像分割

python - 将一组区间简化为最简单的表示