เมื่อต้องการดึง dictionary ที่ผลรวมค่ามากกว่า K ใช้การวนลูปง่ายและเงื่อนไข 'if'
ตัวอย่าง
สาธิตด้านล่าง:
my_list = [{"Python" : 14, "is" : 18, "fun" : 19}, {"Python" : 12, "is": 4, "fun" : 16}, {"Python" : 13, "is": 17, "fun" : 11}, {"Python" : 13, "is": 16, "fun" : 13}]
print("The list :")
print(my_list)
K = 35
print("The value for K :")
print(K)
my_result = []
for index in my_list:
sum = 0
for key in index:
sum += index[key]
if sum > K:
my_result.append(index)
print("The result is :")
print(my_result)
ผลลัพธ์
The list : [{'Python': 14, 'is': 18, 'fun': 19}, {'Python': 12, 'is': 4, 'fun': 16}, {'Python': 13, 'is': 17, 'fun': 11}, {'Python': 13, 'is': 16, 'fun': 13}]
The value for K : 35
The result is : [{'Python': 14, 'is': 18, 'fun': 19}, {'Python': 13, 'is': 17, 'fun': 11}, {'Python': 13, 'is': 16, 'fun': 13}]
คำอธิบาย
- กำหนดลิสต์ของ dictionary และแสดงผล
- กำหนดค่า K และแสดงผล
- สร้างลิสต์ว่าง
- วนลูปลิสต์ กำหนด sum = 0
- ถ้ามี key ใน index ให้บวกค่าเข้า sum
- ถ้า sum > K ให้ append index เข้าไปในลิสต์ว่าง
- แสดงลิสต์ผลลัพธ์บนคอนโซล