Python dictionary doesn't have all the keys assigned, or items

后端 未结 4 1336
刺人心
刺人心 2021-01-17 07:44

I created the following dictionary

exDict = {True: 0, False: 1, 1: \'a\', 2: \'b\'}

and when I print exDict.keys(), well, it g

4条回答
  •  春和景丽
    2021-01-17 08:02

    What you are seeing is python coercing the 1 to be equal to the True.

    You'll see that the dictionary you print is:

    False  1
    True   a
    2      b
    

    Where the value a was meant to be assigned to the 1, but instead the value for True got reassigned to a.

    According to the Python 3 Documentation:

    The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

    Emphasis mine.

    Note: In python 2.X True and False can be re-assigned, so this behavior cannot be guaranteed.

提交回复
热议问题