You can do as follows
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!")
Run
$ python3 test.py
item1 exist!
item2 exist!
item21 exist!
item22 not exist!
item3 not exist!
Check if the dictionary contains the element of the specified key
Recommended Posts