เมื่อจำเป็นต้องกรองพจนานุกรมตามค่าในคีย์ 'K' ในรายการ ระบบจะใช้การวนซ้ำอย่างง่ายโดยการระบุเงื่อนไข
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน
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}] คำอธิบาย
-
รายการพจนานุกรมถูกกำหนดและแสดงบนคอนโซล
-
รายการจำนวนเต็มและคีย์อื่นถูกกำหนดไว้แล้ว
-
มีการกำหนดรายการที่ว่างเปล่า
-
รายการมีการทำซ้ำและหากพบคีย์ องค์ประกอบนั้นจะถูกผนวกเข้ากับรายการอารมณ์
-
นี่คือผลลัพธ์
-
จะแสดงบนคอนโซล