问题描述
对于这个简单的字典-
键1和值“ apple”始终显示为“ 1:False”
有没有我忽略的原因?
$ cat dict.py
CREATE TABLE dbo.MedicalFiles
(
PatientName varchar(50),DoctorName varchar(50),DoctorSpecialy varchar(50),reasonforthevisit varchar(50),doctorvisitcost int,medicationcost int,additionalcostsdescription varchar(50),Additionalcostvalue int,Medicalrecord AS CAST('https://www.google.com' as XML)
);
* $ python3.8 dict.py
pairs = {1: "apple","orange": [2,3,4],True: False,None: "True",}
print(pairs)
谢谢
解决方法
Python中的bool
类型是int
的子类型,其中True
等于数字1
,而False
等于数字0
:
>>> 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,None: 'True'}
虽然这可以解释这种行为,但我确实同意它可能会造成一些混乱。因此,我建议不要使用不同类型的字典键,以免出现这种情况。