
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
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.
- Related Articles
- Ways to sort list of dictionaries by values in Python
- How to sort a list of dictionaries by values of dictionaries in C#?
- Sort list of dictionaries by values in C#
- Ways to sort list of dictionaries by values in Python Using itemgetter
- How do I sort a list of dictionaries by values of the dictionary in Python?
- Ways to sort list of dictionaries by values in Python Using lambda function
- Ways to sort list of dictionaries using values in python
- Python – Sort Dictionaries by Size
- MongoDB Aggregate sum of values in a list of dictionaries for all documents?
- Program to update list items by their absolute values in Python
- Python Program to Sort a Tuple By Values
- Python program to sort a list of tuples by second Item
- Python Program to Sort A List Of Names By Last Name
- Python - Filter dictionaries by values in Kth Key in list
- Python program to sort tuples by frequency of their absolute difference

Advertisements