ดิกชันนารี (Dictionary) ถูกใช้ในหลายๆ การประยุกต์ใช้งานจริง เช่น การเขียนโปรแกรมประจำวัน พัฒนาเว็บ และการเขียนโปรแกรม AI/ML ทำให้มันเป็นคอนเทนเนอร์ที่มีประโยชน์โดยรวม ดังนั้น การรู้จักวิธีการทำงานต่างๆ ที่เกี่ยวข้องกับการใช้งานดิกชันนารี จะเป็นประโยชน์มาก
ตัวอย่างโค้ด
1. ใช้คำสั่ง del
# ใช้ del
# เริ่มต้นดิกชันนารี
test_dict = {"Vishesh": 29, "Ram": 21, "Vishal": 27, "Prashant": 25}
# แสดงดิกชันนารีก่อนลบ
print("The dictionary before performing remove is : " + str(test_dict))
# ใช้ del เพื่อลบคีย์
del test_dict['Vishal']
# แสดงดิกชันนารีหลังลบ
print("The dictionary after remove is : " + str(test_dict))
2. ใช้เมธอด pop()
# ใช้ pop()
# เริ่มต้นดิกชันนารี
test_dict = {"Vishesh": 29, "Ram": 21, "Vishal": 27, "Prashant": 25}
# แสดงดิกชันนารีก่อนลบ
print("The dictionary before performing remove is : " + str(test_dict))
# ใช้ pop() เพื่อลบคีย์-ค่า
removed_value = test_dict.pop('Ram')
# แสดงดิกชันนารีหลังลบ
print("The dictionary after remove is : " + str(test_dict))
print("The removed key's value is : " + str(removed_value))
# ใช้ pop() พร้อมค่าเริ่มต้น (ไม่โยน exception ถ้าคีย์ไม่มี)
removed_value = test_dict.pop('Nilesh', 'No Key found')
print("The dictionary after remove is : " + str(test_dict))
print("The removed key's value is : " + str(removed_value))
3. ใช้ items() ร่วมกับ Dictionary Comprehension
# ใช้ items() + dict comprehension
# เริ่มต้นดิกชันนารี
test_dict = {"Vishesh": 29, "Ram": 21, "Vishal": 27, "Prashant": 25}
# แสดงดิกชันนารีก่อนลบ
print("The dictionary before performing remove is : " + str(test_dict))
# ใช้ items() + dict comprehension เพื่อสร้างดิกชันนารีใหม่โดยไม่รวมคีย์ที่ต้องการลบ
new_dict = {key: val for key, val in test_dict.items() if key != 'Prashant'}
# แสดงดิกชันนารีหลังลบ
print("The dictionary after remove is : " + str(new_dict))
สรุป
- del - ลบคีย์โดยตรง จะโยน KeyError ถ้าคีย์ไม่มีอยู่
- pop() - ลบคีย์และคืนค่า สามารถระบุค่าเริ่มต้นได้เพื่อป้องกัน error
- Dictionary Comprehension - สร้างดิกชันนารีใหม่โดยกรองคีย์ที่ไม่ต้องการ เหมาะสำหรับการลบหลายคีย์พร้อมกัน