==操作符在Python字典上实际执行什么? [英] What does the == operator actually do on a Python dictionary?

查看:118
本文介绍了==操作符在Python字典上实际执行什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑:

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

根据python文档,你确实可以使用 == 操作符在字典上

According to the python doc, you can indeed use the == operator on dictionaries.

这里实际发生了什么? Python是递归地检查字典的每个元素以确保相等吗?是否确保密钥相同匹配,并且值也相同匹配?

What is actually happening here? Is Python recursively checking each element of the dictionaries to ensure equality? Is it making sure the keys are identically matched, and the values are also identically matched?

是否有文档指定什么 == <字典上的code>意味着?或者我是否必须实现我自己的平等检查版本?

Is there documentation that specifies exactly what == on a dictionary means? Or whether I have to implement my own version of checking for equality?

(如果 == 为什么我们不能创建一个可以分类的数组?也就是说,为什么我不能创建一个set()的dicts,或者使用一个dict作为字典键?)

(If the == operator works, why aren't dicts hashable? That is, why can't I create a set() of dicts, or use a dict as a dictionary key?)

推荐答案

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

Python is recursively checking each element of the dictionaries to ensure equality. See the C dict_equal() implementation, which checks each and every key and value (provided the dictionaries are the same length); if dictionary b has the same key, then a PyObject_RichCompareBool tests if the values match too; this is essentially a recursive call.

字典不可哈希,因为它们的 __ hash __ 属性设置为 ,最重要的是 mutable ,当用作字典键时不允许。

Dictionaries are not hashable because their __hash__ attribute is set to None, and most of all they are mutable, which is disallowed when used as a dictionary key.

如果要使用字典作为键,并通过现有的引用更改密钥,那么该密钥将不再插入哈希表中的相同位置。使用另一个相同的字典(等于不变的字典或更改的字典)尝试和检索该值现在将不再工作,因为错误的插槽将被选中,或者键将不再是相等的。

If you were to use a dictionary as a key, and through an existing reference then change the key, then that key would no longer slot to the same position in the hash table. Using another, equal dictionary (be it equal to the unchanged dictionary or the changed dictionary) to try and retrieve the value would now no longer work because the wrong slot would be picked, or the key would no longer be equal.

这篇关于==操作符在Python字典上实际执行什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆