将具有相同散列的两个键放入dict [英] Putting two keys with the same hash into a dict
问题描述
>>> one_decimal = Decimal('1')
>>> one_complex = complex(1,0)
>>> d = {one_decimal: '1D', one_complex: '1C'}
>>> map(hash, d)
[1, 1]
为什么dict允许有多个插槽占用,那些键哈希一样?
Why does the dict allow to have multiple slots occupied, when those keys hash the same?
>>> d[1]
'1D'
>>> d[1+0j]
'1C'
索引管理如何解决一个复杂的文字索引的正确值?为什么这些数字相等,当它们都等于 int(1)
?
And how does the indexing manage to resolve the correct value for a complex literal indexing? Why don't these numbers compare equal, when they're both equal to int(1)
?
Python 2.7.12。
Python 2.7.12.
推荐答案
由于表示,哈希的相等并不意味着对象的平等。只要对象本身不相等,Python词典可以包含任意数量的具有相等哈希值的元素。
As the accepted answer mentioned by @CoryKramer states, equality of hashes does not imply equality of objects. Python dictionaries can contain any number of elements with equal hashes as long as the objects themselves are not equal.
您的问题的简短答案可能是执行 complex
类型在2.7版本的Python库中有些不完整。正如@wim所指出的那样,使用 == $ c $ c c
c>工作正常,但是比较
十进制
和复合
不。因为比较 one_decimal == one_complex
将始终返回 False
,因为它们的类型,他们都可以生活在同一个字典中Python 2.7。
The short answer to your question is probably that the implementation of the complex
type is a bit incomplete in the Python library as of 2.7. As @wim points out, comparing int
and complex
using ==
works fine, but comparing Decimal
and complex
does not. Since comparing one_decimal == one_complex
will always return False
because of their types, they can both live in the same dictionary in Python 2.7.
此问题已在Python 3中修复。我在3.5中进行实验,其中 one_decimal
和 one_complex
相等。运行相同的代码段后,字典包含 one_complex
的值 one_decimal
(如第一个键,最后一个值)。
This issue has been fixed in Python 3. I am experimenting in 3.5, where one_decimal
and one_complex
are equal. After running the same snippet, the dictionary contains the value for one_complex
under the key one_decimal
, as expected (first key, last value).
这是Py2.7的复杂的
类型。修正于Py3。
It's a bug in Py2.7's complex
type. Fixed in Py3.
这篇关于将具有相同散列的两个键放入dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!