示例说明:
>>> a = dict(eggs='eggs', spam='spam')
>>> b = dict(spam='spam', ham='ham')
>>> dict(a.items() | b.items())
{'eggs': 'eggs', 'ham': 'ham', 'spam': 'spam'}
同时...
>>> dict(a.items() + b.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'
这是有原因的吗?假设加法和并集对字典也应这样做是否合理?
在Python 2中,这可以很好地工作:
>>> dict(a.items() + b.items())
{'eggs': 'eggs', 'ham': 'ham', 'spam': 'spam'}
尽管在Python 2中,.items()
返回一个常规列表(与dict_items
相比),所以这可能是偶然的。
最后,我不认为“如果键具有不同的值会发生什么”-困境在这里适用,因为算子|
似乎并不介意(两个值中的一个似乎是随机选择的)。 / p>
答案 0 :(得分:3)
某些dict
视图(notably not dict.values
)支持set operations。 +
不是设置操作,因此没有任何真正的理由应该包含它。
答案 1 :(得分:1)
只需在@Patrick的答案中添加一点,dict_items
对象就是collections.Set
的子类
from collections.abc import Set
isinstance(d.items(), Set) # True
和Set
没有+
操作:
'__add__' in dir(Set) # False
答案 2 :(得分:1)
让我们回到最基本的Python口头禅:Zen of Python。
应该有一种-最好只有一种-显而易见的方法。
所以您要问为什么不应该定义+
与|
做相同的事情。您的答案就在那里:有两种同样正确的方式来做同一件事,这不是Pythonic。