Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to Sort a List of Dictionaries by the Sum of their Values
When working with lists of dictionaries, you may need to sort them based on the sum of their values. Python provides multiple approaches to achieve this using the sort() method with custom key functions.
Method 1: Using a Custom Function
Define a function to calculate the sum of dictionary values and use it as the sorting key ?
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:
[{21: 13, 44: 35, 34: 56}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
The result is:
[{48: 29, 17: 53}, {21: 13, 44: 35, 34: 56}, {1: 155}, {11: 75, 70: 19, 39: 70}]
Method 2: Using Lambda Function
A more concise approach uses a lambda function directly in the sort method ?
my_dict = [{21: 13, 44: 35, 34: 56}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
print("Original list:")
print(my_dict)
my_dict.sort(key=lambda x: sum(x.values()))
print("Sorted by sum of values:")
print(my_dict)
Original list:
[{21: 13, 44: 35, 34: 56}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
Sorted by sum of values:
[{48: 29, 17: 53}, {21: 13, 44: 35, 34: 56}, {1: 155}, {11: 75, 70: 19, 39: 70}]
Method 3: Using sorted() for Immutable Sorting
Use sorted() to create a new sorted list without modifying the original ?
my_dict = [{21: 13, 44: 35, 34: 56}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
print("Original list:")
print(my_dict)
sorted_dict = sorted(my_dict, key=lambda x: sum(x.values()))
print("Sorted list:")
print(sorted_dict)
print("Original list (unchanged):")
print(my_dict)
Original list:
[{21: 13, 44: 35, 34: 56}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
Sorted list:
[{48: 29, 17: 53}, {21: 13, 44: 35, 34: 56}, {1: 155}, {11: 75, 70: 19, 39: 70}]
Original list (unchanged):
[{21: 13, 44: 35, 34: 56}, {11: 75, 70: 19, 39: 70}, {1: 155}, {48: 29, 17: 53}]
Comparison
| Method | Modifies Original? | Best For |
|---|---|---|
sort() with function |
Yes | Reusable logic, complex calculations |
sort() with lambda |
Yes | Simple, one-time operations |
sorted() |
No | Preserving original data |
Conclusion
Use lambda functions for simple sorting operations and custom functions for complex logic. Choose sorted() when you need to preserve the original list structure.
Advertisements
