如何檢查 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