==运算符在Python字典上实际做什么?

2024-06-01 01:07:06 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑:

>>> a = {'foo': {'bar': 3}}
>>> b = {'foo': {'bar': 3}}
>>> a == b
True

根据python文档,you can indeed use字典上的==运算符。

这里到底发生了什么?Python是否递归地检查字典中的每个元素以确保相等?它是否确保键完全匹配,并且值也完全匹配?

有没有文档确切地说明字典上的==是什么意思?或者我是否必须实现我自己的检查平等的版本?

(如果==运算符起作用,为什么dicts不可哈希?也就是说,为什么我不能创建dict的set()或使用dict作为字典键?)


Tags: 文档版本youtrue元素字典foouse
3条回答

Python递归地检查字典的每个元素以确保相等。请参阅C ^{} implementation,它检查每个键和值(前提是字典的长度相同);如果字典b具有相同的键,则PyObject_RichCompareBool测试值是否也匹配;这本质上是一个递归调用。

字典是不可散列的,因为它们的^{} attribute is set to ^{},而且最重要的是它们是可变的,这在用作字典键时是不允许的。

如果使用字典作为键,并通过现有引用更改键,则该键将不再在哈希表中的同一位置插入。使用另一个相等的字典(无论它等于未更改的字典还是已更改的字典)尝试检索该值现在将不再工作,因为将选择错误的槽,或者键将不再相等。

如果字典具有相同的键和每个键的相同值,则字典是相等的。

请参见一些示例:

dict(a=1, b=2) == dict(a=2, b=1)
False

dict(a=1, b=2) == dict(a=1, b=2, c=0)
False

dict(a=1, b=2) == dict(b=2, a=1)
True

来自docs

Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equal .[5] Outcomes other than equality are resolved consistently, but are not otherwise defined. [6]

脚注[5]

The implementation computes this efficiently, without constructing lists or sorting.

脚注[6]

Earlier versions of Python used lexicographic comparison of the sorted (key, value) lists, but this was very expensive for the common case of comparing for equality. An even earlier version of Python compared dictionaries by identity only, but this caused surprises because people expected to be able to test a dictionary for emptiness by comparing it to {}.

相关问题 更多 >