บทความนี้สาธิตวิธีลบ Dictionary ออกจากลิสต์ของ Dictionary เมื่อไม่พบค่าที่ระบุในคีย์ที่กำหนด
โค้ดตัวอย่าง
# ลิสต์ของ Dictionary
my_list = [
{"code": 1, "fun": "learn"},
{"code": 2, "fun": "code"},
{"code": 3, "fun": "test"},
{"code": 4, "fun": "teach"},
{"code": 4, "fun": "make"},
{"code": 4, "fun": "object"}
]
print("ลิสต์ต้นฉบับ:")
for item in my_list:
print(f" {item}")
# ลบ Dictionary ที่มี code == 3
# ใช้ลูปย้อนกลับเพื่อป้องกันปัญหา Index เปลี่ยนแปลง
for i in range(len(my_list) - 1, -1, -1):
if my_list[i]['code'] == 3:
del my_list[i]
break # หยุดหลังลบตัวแรกที่เจอ (ถ้าต้องการลบทั้งหมด ให้ลบ break ออก)
print("\nลิสต์หลังลบ code == 3:")
for item in my_list:
print(f" {item}")
ผลลัพธ์
ลิสต์ต้นฉบับ:
{'code': 1, 'fun': 'learn'}
{'code': 2, 'fun': 'code'}
{'code': 3, 'fun': 'test'}
{'code': 4, 'fun': 'teach'}
{'code': 4, 'fun': 'make'}
{'code': 4, 'fun': 'object'}
ลิสต์หลังลบ code == 3:
{'code': 1, 'fun': 'learn'}
{'code': 2, 'fun': 'code'}
{'code': 4, 'fun': 'teach'}
{'code': 4, 'fun': 'make'}
{'code': 4, 'fun': 'object'}
วิธีที่ดีกว่า: List Comprehension
# กรองเก็บเฉพาะที่ code != 3 (อ่านง่ายกว่าและปลอดภัยกว่า)
my_list = [d for d in my_list if d['code'] != 3]
# หรือถ้าต้องการลบหลายเงื่อนไข
my_list = [d for d in my_list if d['code'] not in [3, 4]]
ข้อควรระวัง
- อย่าใช้ for loop แบบปกติพร้อม del - จะทำให้ Index เลื่อนและข้ามรายการ
- ใช้ ลูปย้อนกลับ (reverse loop) หรือ List Comprehension แทน
breakจะหยุดหลังลบตัวแรก - ลบออกถ้าต้องการลบทุกตัวที่ตรงเงื่อนไข
การประยุกต์ใช้
เหมาะสำหรับการทำความสะอาดข้อมูล เช่น:
- ลบรายการที่ข้อมูลไม่ครบ
- ลบข้อมูลที่ไม่ผ่านการตรวจสอบ (Validation)
- กรองข้อมูลตามเงื่อนไขทางธุรกิจ