Python の辞書にキーが存在するかどうかを確認する方法

Jinku Hu 2020年6月25日 2018年3月6日
Python の辞書にキーが存在するかどうかを確認する方法

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
情報

特定のキーがディクショナリに存在するかどうかを確認する他のソリューションがあるかもしれません。たとえば、

if key in dicObj.keys()

先ほど示したソリューションでも同じ結果が得られます。しかし、この dicObj.keys() メソッドは、辞書キーをリストに変換するのに余分な時間がかかるため、およそ 4 倍遅くなります。

以下の実行時パフォーマンス比較テストを参照できます。

>>> 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
Jinku Hu avatar Jinku Hu avatar

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

関連記事 - Python Dictionary