字典强制有意还是不? [英] Dictionary coercion intentional or no?
问题描述
如果我写:
d = { 0:'a', 1:'b' }
d[False] = 'c'
d[True] = 'd'
print(d)
我得到:
{ 0:'c', 1:'d' }
为什么会强制他们进入int?它是相同的事情相反。
Why is it coercing them into ints? It does the same thing in reverse.
d = {False:'a', True:'b'}
d[0] = 'c'
d[1] = 'd'
print(d)
输出是:
{False:'c', True: 'd'}
可以禁用吗?这是一个错误吗?
Can this be disabled? Is it a bug?
推荐答案
这是因为这些值被认为是相等的:
It's because those values are considered equal:
>>> True == 1
True
>>>
>>> False == 0
True
并具有相同的哈希值:
>>> hash(True), hash(1)
(1, 1)
>>>
>>> hash(False), hash(0)
(0, 0)
因此,字典的观点, True
和 1
是不可区分的,因为 False
和 0
。
Therefore, from the dictionary's point of view, True
and 1
are indistinguishable as are False
and 0
.
没有办法禁用这个 - 你不应该在dict中使用非均匀密钥开始。
There is no way to "disable" this -- you shouldn't be using non-homogenous keys in a dict to begin with.
在这种具体情况下,潜在的解决方法是为 True
和 False
除 1
和 0
(假设你需要 1
和 0
作为独立的键)。例如,您可以有 -1
代表 True
和 -2
代表 False
。
A potential workaround in this specific case would be to reserve special int values for True
and False
other than 1
and 0
, respectively (presuming you need 1
and 0
as independent keys). For instance, you could have -1
represent True
and -2
represent False
.
这篇关于字典强制有意还是不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!