python 词典的奇怪行为

Strange behavior with python dictionary

我在学习 python 哈希函数时遇到了以下行为。

>>> hash(-1)
-2
>>> hash(-2)
-2

SO 已经有一个很棒的 post 可以回答为什么:Why do -1 and -2 both hash to -2 in CPython?

由于 python 字典使用键的散列来存储值,因此预期会出现以下输出,因为 True1 具有相同的散列:

>>> my_dict = { True: "true", 1: "one"}
>>> my_dict
{True: 'one'}
>>> hash(True)
1
>>> hash(1)
1

但是如果我尝试以下操作,我希望输出为 { -1: "Minus Two"},因为 -1-2 具有相同的哈希值。但事实并非如此。

>>> my_dict = { -1: "Minus One", -2: "Minus Two"}
>>> my_dict
{-1: 'Minus One', -2: 'Minus Two'}
>>> hash(-1)
-2
>>> hash(-2)
-2

这种行为的原因是什么?。字典不使用键的散列来存储它的值吗?

注意:我知道这是 CPython 特有的,但我很想知道这种行为的原因。

它不仅检查对象的哈希值,还检查对象的相等性。你可以通过这个例子看到这个效果:

>>> class Samesies:
...     def __hash__(self):
...             return 1
...     def __eq__(self, other):
...             return True
...
>>> {Samesies(): 1, Samesies(): 2}
{<__main__.Samesies object at 0x0000023997ACEFA0>: 2}

编辑:1 == Truehash(1) == hash(True) 的原因是 bool 实际上是 int.

的子类