为什么我不能使用“+”来合并 Python 中的词典?

Why can't I use '+' to merge dictionaries in Python?

我是新 Python 用户,我会有一些疑问。

我知道 + 运算符不仅执行数字之间的求和,还执行字符串或列表之间的连接。为什么字典不允许这样做?

字典的 + 运算符如何处理重复键?例如

>>> {'d': 2} + {'d': 1}

也许像 Counter?

>>> from collections import Counter
>>> Counter({'d': 2}) + Counter({'d': 1})
Counter({'d': 3})

或者喜欢defaultdict

{'d': [2, 1]}

或者像dict.update一样覆盖第一个键?

>>> d = {'d': 2}
>>> d.update({'d':1})
>>> d
{'d': 1}

或者只留下第一个键?

{'d': 2}

坦率地说是模棱两可的!

另见 PEP 0584:

Use The Addition Operator

This PEP originally started life as a proposal for dict addition, using the + and += operator. That choice proved to be exceedingly controversial, with many people having serious objections to the choice of operator. For details, see previous versions of the PEP and the mailing list discussions.

请注意 Guido 本人 consider and discuss this; see also issue36144

在 Python 3.9 :)

中有一个被接受的 PEP

https://www.python.org/dev/peps/pep-0584/#specification

d = {'spam': 1, 'eggs': 2, 'cheese': 3}

e = {'cheese': 'cheddar', 'aardvark': 'Ethel'}

d | e {'spam': 1, 'eggs': 2, 'cheese': 'cheddar', 'aardvark': 'Ethel'}

e | d {'aardvark': 'Ethel', 'spam': 1, 'eggs': 2, 'cheese': 3}