合并字典时出现 TypeError:不支持 | 的操作数类型:'dict' 和 'dict'

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

我想使用 | 运算符连接两个词典,但出现以下错误:

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

字典的合并 (|) 和更新 (|=) 运算符是 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)