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

Python – ลบ Dictionary ที่มีค่า Key ตรงกัน

เมื่อต้องการลบ dictionary ออกจากลิสต์ถ้าค่าของ key ที่กำหนด (K) ตรงกับ dictionary ในลิสต์อีกอันหนึ่ง สามารถใช้ dictionary comprehension ได้

ตัวอย่าง

my_dict_1 = [{'Hi': 32, "there": 32, "Will": 19}, {'Hi': 19, "there": 100, "Will": 13}, {'Hi': 72, "there": 19, "Will": 72}]
print("The first dictionary is : ")
print(my_dict_1)
my_dict_2 = [{'Hi': 72, "Will": 19}, {"Will": 13, "Hi": 19}]
print("The second dictionary is : ")
print(my_dict_2)
K = "Hi"
print("The value of K is ")
print(K)
temp = {element[K] for element in my_dict_2}
my_result = [element for element in my_dict_1 if element[K] not in temp]
print("The result is : ")
print(my_result)

ผลลัพธ์

The first dictionary is : [{'Hi': 32, 'there': 32, 'Will': 19}, {'Hi': 19, 'there': 100, 'Will': 13}, {'Hi': 72, 'there': 19, 'Will': 72}]
The second dictionary is : [{'Hi': 72, 'Will': 19}, {'Will': 13, 'Hi': 19}]
The value of K is Hi
The result is : [{'Hi': 32, 'there': 32, 'Will': 19}]

คำอธิบาย

  • กำหนดสองลิสต์ของ dictionary และ key K ที่นำไปเปรียบเทียบ

  • สร้าง set temp ของค่า key K จากลิสต์ที่สอง (72, 19)

  • ใช้ list comprehension กรองลิสต์แรก: เก็บเฉพาะ dictionary ที่ element[K] ไม่อยู่ใน temp

  • แสดงผลลัพธ์ (เฉพาะ dictionary แรกที่ Hi=32 ไม่อยู่ใน temp)