【问题标题】:TypeError when merging dictionaries: unsupported operand type(s) for |: 'dict' and 'dict'合并字典时出现类型错误:|: 'dict' 和 'dict' 不支持的操作数类型
【发布时间】:2020-10-11 09:06:11
【问题描述】:

我想使用| 运算符加入两个字典,但出现以下错误:

TypeError: unsupported operand type(s) for |: 'dict' and 'dict'

MWE 代码如下:

d1 = {'k': 1, 'l': 2, 'm':4}
d2 = {'g': 3, 'm': 7}

e = d1 | d2

【问题讨论】:

  • 是的,我们鼓励自己提出问题并自己回答,但这个似乎非常接近the other question you posted before,不是吗?
  • 预期当字典合并和更新操作将变得更流行时人们将要寻找的问题,而引入它们时的确切版本的 python - 不记得了。我真的不确定那些偶然发现标题错误的人会深入研究其他问题/答案。
  • 好的,这就是我以为你在做的事情:D 我不知道这是在 SO 中完成的,但我是社区中的新手,所以请不要介意。
  • d1 末尾有一个 '
  • @Alechan:已修复。感谢您的发现。

标签: python python-3.x dictionary typeerror python-3.8


【解决方案1】:

字典的合并 (|) 和更新 (|=) 运算符是 introduced in Python 3.9,因此它们在旧版本中不起作用。您可以选择将 Python 解释器更新为 Python 3.9 或使用其中一种替代方法:

# option 1:
e = d1.copy()
e.update(d2)

# option 2:
e = {**d1, **d2}

但是,如果您想更新到 Python 3.9,您可以直接保存一些内存更新字典 d1,而不是使用就地合并操作创建另一个字典:

d1 |= d2

在旧版本的 Python 中相当于以下内容:

d1.update(d2)

【讨论】:

    猜你喜欢
    • 2022-08-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 2015-03-29
    • 1970-01-01
    • 2022-06-17
    • 2017-05-27
    • 2014-06-15
    相关资源
    最近更新 更多