Skip to main content
 首页 » 编程设计

python之为什么字典 (dict_items) 支持并集 (__or__) 但不支持加法 (__add__)

2025年05月04日20mq0036

举例说明:

>>> 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 对比),所以这可能是偶然的。


最后,我不认为“如果键有不同的值会发生什么”——困境适用于这里,因为运算符 | 似乎并不介意(两个值之一似乎是随机选择的) ).

请您参考如下方法:

一些 dict View ( notably not dict.values ) 支持 set operations . + 不是集合操作,因此没有理由包含它。