为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

明月笑刀无情 2023-12-29 15:33:30
对于这个简单的字典 -键 1 和值“apple”始终打印为“1:False”我忽略了这个原因吗?$ 猫字典.pypairs = {1: "apple",    "orange": [2, 3, 4],     True: False,     None: "True",}print(pairs)* $ python3.8 字典.py{1: False, 'orange': [2, 3, 4], None: 'True'}谢谢
查看完整描述

1 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

Python 中的类型是where equals the number和equals the numberbool的子类型:intTrue1False0


>>> True == 1

True

>>> False == 0

True

当这些值被散列时,它们也会产生相同的值:


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

虽然这解释了这种行为,但我确实同意它可能有点令人困惑。因此,我建议不要使用不同类型的字典键,以免遇到这种情况。


查看完整回答
反对 回复 2023-12-29
  • 1 回答
  • 0 关注
  • 39 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信