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

Python – เรียงลำดับลิสต์ Dictionary ตามผลรวมค่า Value

เมื่อต้องการเรียงลำดับลิสต์ของ dictionary ตามผลรวมของค่า (values) ในแต่ละ dictionary สามารถใช้ฟังก์ชันช่วยที่มี sum() และ .values() ได้

ตัวอย่าง

def sum_value(row):
    return sum(list(row.values()))

my_dict = [{21: 13, 44: 35, 34: 56}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
print("The dictionary is :")
print(my_dict)
my_dict.sort(key=sum_value)
print("The result is :")
print(my_dict)

ผลลัพธ์

The dictionary is : [{34: 56, 44: 35, 21: 13}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
The result is : [{48: 29, 17: 53}, {34: 56, 44: 35, 21: 13}, {1: 155}, {11: 75, 70: 19, 39: 70}]

คำอธิบาย

  • กำหนดฟังก์ชัน sum_value รับ dictionary ดึง .values() แปลงเป็นลิสต์ หา sum()

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

  • ใช้ sort(key=sum_value) เรียงตามผลรวม value จากน้อยไปมาก

  • ผลรวม: {48:29,17:53}=82, {34:56,44:35,21:13}=104, {1:155}=155, {11:75,70:19,39:70}=164