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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With