检查 dict 中是否存在对象

check to see whether an object exists in dict

提问人:cardinal2000 提问时间:8/7/2023 最后编辑:S.Bcardinal2000 更新时间:8/7/2023 访问量:46

问:

a = {1 : 4}
print(4 in a)     # case 1: False

a = {1 : 's'}
print('s' in a)   # case 2: False

a = {1 : None}
print(None in a)  # case 3: False

a = {1: True}
print(True in a)  # case 4: True

所以我的问题是为什么除了第四种情况外,所有情况都返回 False ?

python-3.x 字典 boolean-expression

评论

0赞 RomanPerekhrest 8/7/2023
它搜索(字典的)键
0赞 cardinal2000 8/7/2023
那么@RomanPerekhrest那么,为什么第四种情况返回 True,而 True 键不存在呢?
0赞 RomanPerekhrest 8/7/2023
它确实以1 == True
0赞 cardinal2000 8/7/2023
@RomanPerekhrest哦,tnx你是对的,我也检查了这个案例,这证明了你的答案 --> a = {0 : 'foo'} print(False in a) # returns False

答:

1赞 S.B 8/7/2023 #1

成员资格测试是针对字典的“键”而不是值进行的。对于值,您可以执行以下操作:

a = {1: 4}
print(4 in a.values())

但请记住,它执行的是线性搜索,而不是 O(1) 键。

对于最后一种情况:

bool是 的子类,等于 。(它们的哈希值当然是一样的)intTrue1

效果基本相同:

s = {1, True}
print(len(s)) # 1

a = {1: 10}
print(a[True]) # 10