Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ตรวจสอบว่าคีย์หลายตัวมีอยู่ในพจนานุกรมหรือไม่ใน Python

ระหว่างการวิเคราะห์ข้อมูลด้วย Python เราอาจต้องตรวจสอบว่ามีค่าบางค่าที่มีอยู่เป็นคีย์ในพจนานุกรม เพื่อให้ส่วนถัดไปของการวิเคราะห์ใช้ได้เฉพาะกับคีย์ที่เป็นส่วนหนึ่งของค่าที่กำหนด ในบทความนี้เราจะดูวิธีบรรลุเป้าหมายนี้

ด้วยตัวดำเนินการเปรียบเทียบ

ค่าที่ต้องตรวจสอบถูกใส่ในเซต จากนั้นเนื้อหาของเซตถูกเปรียบเทียบกับเซตของคีย์ของพจนานุกรม สัญลักษณ์ >= บ่งชี้ว่าคีย์ทั้งหมดจากพจนานุกรมอยู่ในเซตค่าที่กำหนด

ตัวอย่าง

Adict = {"Mon":3, "Tue":11,"Wed":6,"Thu":9}
check_keys={"Tue","Thu"}
# Use comparison
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")

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

All keys are present
All keys are not present

ด้วย all

ในวิธีนี้เราใช้ลูป for เพื่อตรวจสอบทุกค่าให้อยู่ในพจนานุกรม ฟังก์ชัน all คืนค่า true ก็ต่อเมื่อค่าทั้งหมดจากเซต check key อยู่ในพจนานุกรมที่กำหนด

ตัวอย่าง

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")

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

All keys are present
All keys are not present

ด้วย subset

ในวิธีนี้เราเอาค่าที่ต้องค้นหาเป็นเซตและตรวจสอบว่ามันเป็น subset ของคีย์จากพจนานุกรมหรือไม่ สำหรับนี้เราใช้ฟังก์ชัน 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")

Output

การรันโค้ดข้างต้นให้ผลลัพธ์ดังนี้ -

All keys are present
All keys are not present