ระหว่างการวิเคราะห์ชุดข้อมูล เราอาจเจอสถานการณ์ที่เราต้องจัดการกับพจนานุกรมที่ว่างเปล่า ในบทความ มอก. เราจะดูวิธีการตรวจสอบว่าพจนานุกรมว่างเปล่าหรือไม่
การใช้ if
เงื่อนไข if ประเมินเป็นจริงหากพจนานุกรมมีองค์ประกอบ มิฉะนั้นจะประเมินเป็นเท็จ ดังนั้นในโปรแกรมด้านล่าง เราจะตรวจสอบความว่างเปล่าของพจนานุกรมโดยใช้เงื่อนไข if เท่านั้น
ตัวอย่าง
dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
if dict1:
print("dict1 is not empty")
else:
print("dict1 is empty")
if dict2:
print("dict2 is not empty")
else:
print("dict2 is empty") ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
dict1 is not empty
dict2 is empty การใช้บูล()
วิธีบูลประเมินเป็นจริงถ้าพจนานุกรมไม่ว่างเปล่า มิฉะนั้นจะประเมินเป็นเท็จ ดังนั้นเราจึงใช้สิ่งนี้ในนิพจน์เพื่อพิมพ์ผลลัพธ์สำหรับความว่างเปล่าของพจนานุกรม
ตัวอย่าง
dict1 = {1:"Mon",2:"Tue",3:"Wed"}
dict2 = {}
# Given dictionaries
print("The original dictionary : " ,(dict1))
print("The original dictionary : " ,(dict2))
# Check if dictionary is empty
print("Is dict1 empty? :",bool(dict1))
print("Is dict2 empty? :",bool(dict2)) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
The original dictionary : {1: 'Mon', 2: 'Tue', 3: 'Wed'}
The original dictionary : {}
Is dict1 empty? : True
Is dict2 empty? : False