Boolean keys with other data types in dictionary

前端 未结 3 576
小蘑菇
小蘑菇 2020-12-12 01:42

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\'}         


        
3条回答
  •  情书的邮戳
    2020-12-12 02:19

    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.

提交回复
热议问题