为什么为字典的键“True”赋值会覆盖同一字典中键“1”的值?

对于这个简单的字典 -


键 1 和值“apple”始终打印为“1:False”


我忽略了这个原因吗?


$ 猫字典.py


pairs = {1: "apple",

    "orange": [2, 3, 4], 

    True: False, 

    None: "True",

}

print(pairs)


* $ python3.8 字典.py


{1: False, 'orange': [2, 3, 4], None: 'True'}


谢谢


明月笑刀无情
浏览 51回答 1
1回答

倚天杖

Python 中的类型是where equals the number和equals the numberbool的子类型:intTrue1False0>>> True == 1True>>> False == 0True当这些值被散列时,它们也会产生相同的值:>>> hash(True)1>>> hash(1)1>>> hash(False)0>>> hash(0)0现在,由于字典键基于哈希和对象相等(首先使用哈希相等来快速找到可能相等的键,然后通过相等进行比较),因此产生相同哈希且相等的两个值将产生相同的值字典中的“槽”。如果您创建也具有此行为的自定义类型,您也可以看到这一点:>>> class CustomTrue:        def __hash__(self):            return 1        def __eq__(self, other):            return other == 1>>> pairs = {        1: "apple",        "orange": [2, 3, 4],         True: False,         None: "True",    }>>> pairs[CustomTrue()] = 'CustomTrue overwrites the value'>>> pairs{1: 'CustomTrue overwrites the value', 'orange': [2, 3, 4], None: 'True'}虽然这解释了这种行为,但我确实同意它可能有点令人困惑。因此,我建议不要使用不同类型的字典键,以免遇到这种情况。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python