Python の辞書にキーが存在するかどうかを確認する方法
Jinku Hu
2020年6月25日
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
情報
特定のキーがディクショナリに存在するかどうかを確認する他のソリューションがあるかもしれません。たとえば、
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
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
- Python で辞書をリストに変換する
- Python でディレクトリのすべてのファイルを取得する方法
- Python 辞書で最大値を求める
- Python 辞書を値でソートする方法
- Python 2 および 3 で 2つの辞書をマージする方法