如何检查 Python 字典中是否存在某键
Jinku Hu
2021年7月18日
2018年3月6日
检查 Python 字典中是否存在给定键的问题属于 Python 成员资格检查的范畴,你可以参阅在成员资格检查操作符教程。
in
关键词用于进行字典成员资格检查。我们来看下面的代码示例,
dic = {"A":1, "B":2}
def dicMemberCheck(key, dicObj):
if key in dicObj:
print("Existing key")
else:
print("Not existing")
dicMemberCheck("A")
dicMemberCheck("C")
Existing key
Not existing
Tip
你也可以使用其他方法来检查字典中是否存在给定的键,例如,
if key in dicObj.keys()
它的结果跟上面的方法是意义的,但是这种 dicObj.keys()
方法大约慢了四倍,因为将字典键转换为列表需要花费额外的时间。
下面列出了执行时间性能比较测试的结果,一目了然。
>>> import timeit
>>> timeit.timeit('"A" in dic', setup='dic = {"A":1, "B":2}',number=1000000)
0.053480884567733256
>>> timeit.timeit('"A" in dic.keys()', setup='dic = {"A":1, "B":2}',number=1000000)
0.21542178873681905
Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn