Python program to Sort a List of Dictionaries by the Sum of their Values


When it is required to sort a list of dictionaries based on the sum of their values, a method is defined that uses the ‘sum’ method to determine the result.

Below is a demonstration of the same −

Example

 Live Demo

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)

Output

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}]

Explanation

  • A method named 'sum_value' is defined that takes row as parameter and returns the sum of the row values using the ‘.values’ and ‘sum’ method.

  • A dictionary of integers is defined and is displayed on the console.

  • The dictionary is sorted and the method is called by passing the key as the previously defined value.

  • This is the output that is displayed on the console.

Updated on: 06-Sep-2021

129 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements