字典强制有意还是不? [英] Dictionary coercion intentional or no?

查看:135
本文介绍了字典强制有意还是不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写:

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屋!

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