0
0

More than 3 years have passed since last update.

pythonで、定義された辞書に指定したキーが存在するかを調べた際のメモ

Last updated at Posted at 2020-11-14

以下の通りすればよい

test.py
mydict = {
      "item1":"aaa",
      "item2": {
        "item21": "ddd",
      }
}

if "item1" in mydict:
    print("item1 exist!")
else:
    print("item1 not exist!")

if "item2" in mydict:
    print("item2 exist!")

    teststring = "item2"
    testmatrix = mydict[teststring]
    if "item21" in testmatrix:
        print("item21 exist!")
    else:
        print("item21 not exist!")

    if "item22" in testmatrix:
        print("item22 exist!")
    else:
        print("item22 not exist!")

else:
    print("item2 not exist!")

if "item3" in mydict:
    print("item3 exist!")
else:
    print("item3 not exist!")

実行

$ python3 test.py
item1 exist!
item2 exist!
item21 exist!
item22 not exist!
item3 not exist!

参考

辞書に指定したキーの要素が含まれているか確認する

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0