字典中具有其他数据类型的布尔键 [英] Boolean keys with other data types in dictionary

查看:81
本文介绍了字典中具有其他数据类型的布尔键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看一些python字典链接,并找到了这个.

I was going through some python dictionary links and found this.

我似乎无法理解下面发生的事情.

I can't seem to understand what is happening underneath.

dict1 = {1:'1',2:'2'}
print dict1

输出

{1:'1',2:'2'}

但是,如果我在字典中添加一个布尔键,它会产生一些怪异的东西.

But if I add a boolean key to the dictionary, it gives something weird.

dict2 = {True:'yes',1:'1',2:'2'}
print dict2

输出

{True:'1',2:'2'}

只有在我们将布尔值包含在字典中时才会发生这种情况吗?

Does it only happen if we include Boolean into the dictionary?

推荐答案

问题是True是值为1的内置枚举.因此,哈希函数将True视为另一个1,并且……如您所见,两者在重新映射时会感到困惑.是的,有一些牢固的规则描述了Python将如何解释它们,但是在此级别上,您可能不关心False = 0和True = 1之后的任何内容.

The problem is that True is a built-in enumeration with a value of 1. Thus, the hash function sees True as simply another 1, and ... well, the two get confused on re-mapping, as you see. Yes, there are firm rules that describe how Python will interpret these, but you probably don't care about anything past False=0 and True=1 at this level.

您看到的标签(例如,True vs 1,)设置在第一个参考上.例如:

The label you see (True vs 1, for example) is set at the first reference. For instance:

>>> d = {True:11, 0:10}
>>> d
{0: 10, True: 11}
>>> d[1] = 144
>>> d
{0: 10, True: 144}
>>> d[False] = 100
>>> d
{0: 100, True: 144}

请注意这是如何工作的:每个字典条目显示每个给定值(0/False和1/True)的 first 标签.与所有分配一样,显示的值是最后一个.

Note how this works: each dictionary entry displays the first label is sees for each given value (0/False and 1/True). As with any assignment, the value displayed is that last one.

这篇关于字典中具有其他数据类型的布尔键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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