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

ตรวจสอบว่าพจนานุกรมว่างเปล่าหรือไม่ใน Python

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

ใช้คำสั่ง if

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

ตัวอย่าง

dict1 = {1: "Mon", 2: "Tue", 3: "Wed"}
dict2 = {}
# พจนานุกรมที่กำหนด
print("The original dictionary : ", (dict1))
print("The original dictionary : ", (dict2))

# ตรวจสอบว่าพจนานุกรมว่างเปล่าหรือไม่
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

ใช้ bool()

เมธอด bool จะคืนค่า True หากพจนานุกรมไม่ว่างเปล่า มิฉะนั้นจะคืนค่า False เราสามารถนำไปใช้ในนิพจน์เพื่อแสดงผลความว่างเปล่าของพจนานุกรม

ตัวอย่าง

dict1 = {1: "Mon", 2: "Tue", 3: "Wed"}
dict2 = {}
# พจนานุกรมที่กำหนด
print("The original dictionary : ", (dict1))
print("The original dictionary : ", (dict2))

# ตรวจสอบว่าพจนานุกรมว่างเปล่าหรือไม่
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