ในระหว่างการวิเคราะห์ข้อมูลโดยใช้ python เราอาจต้องตรวจสอบว่ามีค่าสองสามค่าเป็นคีย์ในพจนานุกรมหรือไม่ เพื่อให้ส่วนถัดไปของการวิเคราะห์สามารถใช้ได้เฉพาะกับคีย์ที่เป็นส่วนหนึ่งของค่าที่กำหนด ในบทความนี้เราจะมาดูกันว่าจะสำเร็จได้อย่างไร
ด้วยตัวดำเนินการเปรียบเทียบ
ค่าที่จะตรวจสอบจะถูกใส่เข้าไปในชุด จากนั้นเนื้อหาของชุดจะถูกเปรียบเทียบกับชุดคีย์ของพจนานุกรม สัญลักษณ์>=แสดงว่าคีย์ทั้งหมดจากพจนานุกรมมีอยู่ในชุดค่าที่กำหนด
ตัวอย่าง
Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}
# Use comaprision
if(Adict.keys()) >= check_keys:
print("All keys are present")
else:
print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
if(Adict.keys()) >= check_keys:
print("All keys are present")
else:
print("All keys are not present") ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
All keys are present All keys are not present
พร้อมทุกอย่าง
ในแนวทางนี้เราใช้ for loop เพื่อตรวจสอบทุกค่าที่มีอยู่ในพจนานุกรม ฟังก์ชัน all คืนค่า true ต่อเมื่อค่าทั้งหมดจากชุดคีย์ตรวจสอบมีอยู่ในพจนานุกรมที่กำหนด
ตัวอย่าง
Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}
# Use all
if all(key in Adict for key in check_keys):
print("All keys are present")
else:
print("All keys are not present")
# Check for new keys
check_keys={"Mon","Fri"}
if all(key in Adict for key in check_keys):
print("All keys are present")
else:
print("All keys are not present") ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
All keys are present All keys are not present
พร้อมเซ็ตย่อย
ในแนวทางนี้ เราจะใช้ค่าเพื่อค้นหาเป็นชุดและตรวจสอบว่าเป็นชุดย่อยของคีย์จากพจนานุกรมหรือไม่ สำหรับสิ่งนี้ เราใช้ฟังก์ชัน issubset
ตัวอย่าง
Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys=set(["Tue","Thu"])
# Use all
if (check_keys.issubset(Adict.keys())):
print("All keys are present")
else:
print("All keys are not present")
# Check for new keys
check_keys=set(["Mon","Fri"])
if (check_keys.issubset(Adict.keys())):
print("All keys are present")
else:
print("All keys are not present") ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
All keys are present All keys are not present