ตรวจสอบว่า key ที่กำหนดมีอยู่ใน dictionary หรือไม่
ใช้ in operator
if check_key in Adict: ...
ตัวอย่าง
Adict = {'Mon': 3, 'Tue': 5, 'Wed': 6, 'Thu': 9}
print("The given dictionary : ", Adict)
check_key = "Fri"
if check_key in Adict:
print(check_key, "is Present.")
else:
print(check_key, "is not Present.")
ผลลัพธ์
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}
Fri is not Present.
ใช้ dict.keys()
if check_key in Adict.keys(): ...
ตัวอย่าง
Adict = {'Mon': 3, 'Tue': 5, 'Wed': 6, 'Thu': 9}
print("The given dictionary : ", Adict)
check_key = "Wed"
if check_key in Adict.keys():
print(check_key, "is Present.")
else:
print(check_key, "is not Present.")
ผลลัพธ์
The given dictionary : {'Thu': 9, 'Wed': 6, 'Mon': 3, 'Tue': 5}
Wed is Present.