python - 为什么可变实体不能是字典键?

标签 python dictionary

考虑以下 Python 解释器 shell session :

>>> class D(dict):
...   def __hash__(self):
...     return id(self)
... 
>>> d1 = D({'a': 'b'})
>>> d2 = D({'a1': 'b1'})
>>> t = {d1: 1, d2: 2}
>>> t[d1]
1
>>> t[d2]
2

为什么字典的 __hash__ 不默认为 id()?是什么导致了禁止使用可变实体作为字典键的设计决策?

最佳答案

Why doesn't dict's __hash__ default to id()?

因为这违反了相等对象具有相等哈希值的基本不变量。如果字典使用它们的 id 作为它们的哈希值,那么您将进行如下交互:

>>> x, y = {}, {}
>>> x == y
True
>>> hash(x) == hash(y)
False
>>> x[{}] = 3
>>> x[{}]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: {}

该行为会令人困惑、不一致且无用。

关于python - 为什么可变实体不能是字典键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37197862/

相关文章:

python - Python3.3.5如何在字符串中添加数字和字母(最终结果应该是int)?

dictionary - 如何(不安全地)将 map 反射(reflect)为约束?

c# - 用于模型绑定(bind)到字典的 HTML Helper

要听写的元组的 Python 列表

python - Python 中的 n**n**n 启发式

Python - GAE - 脚本循环消耗大量内存

python - 使用 Python 替换或交换文件中的子字符串

dictionary - 具有固定大小的 Golang 并发访问映射/数组

python - 从嵌套字典列表中获取 Pandas 数据框

Python文件搜索行并在匹配后返回特定行数