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

Python - กรอง Dictionary ในลิสต์ตามค่าของ Key ที่ K (Kth Key)


ตัวอย่าง

โค้ดด้านล่างกรอง dictionary ในลิสต์ โดยตรวจสอบว่าค่าของ key ที่กำหนด (เช่น "is") อยู่ในลิสต์ค่าที่ต้องการหรือไม่

my_list = [{"Python": 2, "is": 4, "cool": 11}, {"Python": 5, "is": 1, "cool": 1}, {"Python": 7, "is": 3, "cool": 7}, {"Python": 9, "is": 9, "cool": 8}, {"Python": 4, "is": 10, "cool": 6}]
print("The list is :")
print(my_list)
search_list = [1, 9, 8, 4, 5]
key = "is"
my_result = []
for sub in my_list:
    if sub[key] in search_list:
        my_result.append(sub)
print("The result is :")
print(my_result)

ผลลัพธ์

The list is : [{'Python': 2, 'is': 4, 'cool': 11}, {'Python': 5, 'is': 1, 'cool': 1}, {'Python': 7, 'is': 3, 'cool': 7}, {'Python': 9, 'is': 9, 'cool': 8}, {'Python': 4, 'is': 10, 'cool': 6}]
The result is : [{'Python': 2, 'is': 4, 'cool': 11}, {'Python': 5, 'is': 1, 'cool': 1}, {'Python': 9, 'is': 9, 'cool': 8}]

คำอธิบาย

  • กำหนดลิสต์ของ dictionary และแสดงผล

  • กำหนดลิสต์ค่าที่ต้องการค้นหา (search_list) และ key ที่จะตรวจสอบ

  • วนลูปผ่านแต่ละ dictionary ถ้าค่าของ key อยู่ใน search_list ให้เพิ่มเข้าไปในลิสต์ผลลัพธ์

  • แสดงผลลัพธ์