Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

python - Boolean keys with other data types in dictionary

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

output

{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

output

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...