Python 字典的视图对象的等价性

Equivalence of view objects of Python dict

Python dict 的查看对象与我预期的比较不同:

a = {0 : 'a', 1 : 'b'}
b = {1 : 'b', 0 : 'a'}

print(a == b) # True
print(a.keys() == b.keys()) # True
print(a.values() == b.values()) # False
print(a.items() == b.items()) # True

为什么 dict.values() 这是 False 有什么特别的原因吗?

其实在相同dict的情况下(连copy都不行),也是False:

a = {0 : 'a', 1 : 'b'}
print(a.values() == a.values()) # False

那么这个视图对象的相等性是什么意思呢?

dict 是无序的,也就是说只要 a 中的所有键都存在于 b 中并且 b 中的所有键都存在于 [=13= 中] 并且这些键的所有值都相等,则两组相等。

如果您尝试检查 ab 是否相同 实例 ,那么您将使用 is

>>> a = {0 : 'a', 1 : 'b'}
>>> b = {1 : 'b', 0 : 'a'}

>>> a is b
False

>>> a = {0 : 'a', 1 : 'b'}
>>> b = a

>>> a is b
True

至于为什么a.values() == b.values()returnsFalse的问题,这是在Python语言中做出的选择。引用自 Python 文档:

An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself:

>>> d = {'a': 1}
>>> d.values() == d.values()
False

字典视图类 实现自己的相等方法。 dict.values()的文档具体说:

An equality comparison between one dict.values() view and another will always return False. This also applies when comparing dict.values() to itself

对于dict.keys()dict.items()dictionary views的文档说:

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

keysitems 视图是类似集合的(或者对于具有不可散列值的 items 视图,大多数情况下是类似集合的)- 它们的行为类似于 set 对象在许多方面,特别是,很容易对此类视图执行 in 测试。这让这些视图支持基于两个视图是否包含相同元素的高效 == 操作。

对于 values 视图,没有很好的方法来实现这样的 == 操作,因此 values 视图 不要 实现任何东西喜欢 ==。它们只是从 object 继承了默认的 __eq__ 实现,因此两个 values 视图只有在它们是同一对象时才会被视为相等。即使对于同一个字典的两个视图,如果它们实际上是同一个视图对象,你只会得到 True

In [2]: x = {}

In [3]: x.values() == x.values()
Out[3]: False

In [4]: v = x.values()

In [5]: v == v
Out[5]: True