Python program to Sort a List of Dictionaries by the Sum of their Values
Last Updated :
21 Apr, 2023
Given Dictionary List, sort by summation of their values.
Input : test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 100}, {8 : 9, 7 : 3}]
Output : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 100}]
Explanation : 12 < 13 < 100, sorted by values sum
Input : test_list = [{1 : 100}, {8 : 9, 7 : 3}]
Output : [{8: 9, 7: 3}, {1: 100}]
Explanation : 12 < 100, sorted by values sum.
Method #1 : Using sort() + sum() + values()
In this, the task of performing sort is done using sort(), and sum() and values() are used to get a summation of all the values of the dictionary.
Python3
def values_sum(row):
return sum ( list (row.values()))
test_list = [{ 1 : 3 , 4 : 5 , 3 : 5 }, { 1 : 7 , 10 : 1 , 3 : 10 }, { 1 : 100 }, { 8 : 9 , 7 : 3 }]
print ( "The original list is : " + str (test_list))
test_list.sort(key = values_sum)
print ( "Sorted Dictionaries List : " + str (test_list))
|
Output:
The original list is : [{1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}, {8: 9, 7: 3}] Sorted Dictionaries List : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}]
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Method #2 : Using sorted() + lambda + sum() + values()
In this, we perform sort using sorted() and provide logic using lambda function.
Python3
test_list = [{ 1 : 3 , 4 : 5 , 3 : 5 }, { 1 : 7 , 10 : 1 , 3 : 10 }, { 1 : 100 }, { 8 : 9 , 7 : 3 }]
print ( "The original list is : " + str (test_list))
res = sorted (test_list, key = lambda row : sum ( list (row.values())))
print ( "Sorted Dictionaries List : " + str (res))
|
Output:
The original list is : [{1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}, {8: 9, 7: 3}] Sorted Dictionaries List : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}]
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Method #4: Using heap data structure
Step-by-step approach:
- Initialize a list of dictionaries named “test_list” with four dictionaries inside it.
- Create an empty heap list named “heap”.
- Iterate through each dictionary in “test_list”.
- Compute the sum of values of the current dictionary using the “sum” function and assign it to a variable named “d_sum”.
- Create a tuple with the current dictionary and its sum of values, and add the tuple to the “heap” list using the “heappush” function from the “heapq” module.
- The tuple is created by placing “d_sum” first and “d” second.
- Create an empty list named “res”.
- Pop each tuple from the “heap” list using the “heappop” function from the “heapq” module. The tuple is unpacked into two variables, but we only need the second one (the dictionary), so we use “_” as a placeholder for the first variable.
- Append the dictionary to the “res” list.
- Repeat steps 7-8 until there are no more tuples in the “heap” list.
- Print the sorted list of dictionaries stored in “res” using the “print” function.
Below is the implementation of the above approach:
Python3
import heapq
test_list = [{ 1 : 3 , 4 : 5 , 3 : 5 }, { 1 : 7 , 10 : 1 , 3 : 10 }, { 1 : 100 }, { 8 : 9 , 7 : 3 }]
heap = []
for d in test_list:
d_sum = sum (d.values())
heapq.heappush(heap, (d_sum, d))
res = []
while heap:
_, d = heapq.heappop(heap)
res.append(d)
print ( "Sorted Dictionaries List : " + str (res))
|
Output
Sorted Dictionaries List : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}]
Time complexity: O(n*logn), where n is the number of dictionaries in the list.
Auxiliary space: O(n), where n is the number of dictionaries in the list.
Method #5: Using a for loop and a dictionary to store the sum of values
Step-by-step approach:
- Initialize an empty dictionary called sum_dict.
- Loop through each dictionary in the list.
- Within the loop, calculate the sum of the values of the current dictionary using the sum() function.
- Add the sum to the sum_dict dictionary with the current dictionary as the key.
- Sort the dictionary sum_dict by value in ascending order using the sorted() function and pass sum_dict.items() as the iterable.
- Initialize an empty list called sorted_list.
- Loop through each tuple in the sorted dictionary and append the dictionary associated with the key to the sorted_list.
- Return the sorted list.
Python3
test_list = [{ 1 : 3 , 4 : 5 , 3 : 5 }, { 1 : 7 , 10 : 1 , 3 : 10 }, { 1 : 100 }, { 8 : 9 , 7 : 3 }]
print ( "The original list is : " + str (test_list))
sum_dict = {}
for d in test_list:
sum_dict[ tuple (d.items())] = sum (d.values())
sorted_dict = sorted (sum_dict.items(), key = lambda x: x[ 1 ])
sorted_list = []
for item in sorted_dict:
sorted_list.append( dict (item[ 0 ]))
print ( "Sorted Dictionaries List : " + str (sorted_list))
|
Output
The original list is : [{1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}, {8: 9, 7: 3}]
Sorted Dictionaries List : [{8: 9, 7: 3}, {1: 3, 4: 5, 3: 5}, {1: 7, 10: 1, 3: 10}, {1: 100}]
Time complexity: O(n log n) for sorting the dictionary, where n is the number of dictionaries in the list.
Auxiliary space: O(n) for the sum_dict dictionary and sorted_list list.
Similar Reads
Python program to sort a dictionary list based on the maximum value
Given list with dictionaries as elements, write a Python program to sort the dictionary on the basis maximum value in a key value pair of a dictionary. In simpler terms, first each element of a list (which is a dictionary) will be checked, meaning each key value pair will be compared to find the ele
5 min read
Sort a List of Python Dictionaries by a Value
Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
3 min read
Sort a List of Dictionaries by a Value of the Dictionary - Python
We are given a list of dictionaries where each dictionary contains multiple key-value pairs and our task is to sort this list based on the value of a specific key. For example, Given the list: students = [{'name': 'David', 'score': 85}, {'name': 'Sophia', 'score': 92}, {'name': 'Ethan', 'score': 78}
2 min read
Python - List of dictionaries all values Summation
Given a list of dictionaries, extract all the values summation. Input : test_list = [{"Apple" : 2, "Mango" : 2, "Grapes" : 2}, {"Apple" : 2, "Mango" : 2, "Grapes" : 2}] Output : 12 Explanation : 2 + 2 +...(6-times) = 12, sum of all values. Input : test_list = [{"Apple" : 3, "Mango" : 2, "Grapes" : 2
5 min read
Python program to sort a list of tuples by second Item
The task of sorting a list of tuples by the second item is common when working with structured data in Python. Tuples are used to store ordered collections and sometimes, we need to sort them based on a specific element, such as the second item. For example, given the list [(1, 3), (4, 1), (2, 2)],
2 min read
Python program to find the sum of dictionary keys
Given a dictionary with integer keys. The task is to find the sum of all the keys. Examples: Input : test_dict = {3 : 4, 9 : 10, 15 : 10, 5 : 7} Output : 32 Explanation : 3 + 9 + 15 + 5 = 32, sum of keys. Input : test_dict = {3 : 4, 9 : 10, 15 : 10} Output : 27 Explanation : 3 + 9 + 15 = 27, sum of
5 min read
Python - Sort Dictionary by Values Summation
Give a dictionary with value lists, sort the keys by summation of values in value list. Input : test_dict = {'Gfg' : [6, 7, 4], 'best' : [7, 6, 5]} Output : {'Gfg': 17, 'best': 18} Explanation : Sorted by sum, and replaced. Input : test_dict = {'Gfg' : [8], 'best' : [5]} Output : {'best': 5, 'Gfg':
4 min read
Python Program to print sum of all key value pairs in a Dictionary
Given a dictionary arr consisting of N items, where key and value are both of integer type, the task is to find the sum of all key value pairs in the dictionary. Examples: Input: arr = {1: 10, 2: 20, 3: 30}Output: 11 22 33Explanation: Sum of key and value of the first item in the dictionary = 1 + 10
5 min read
Python | Summation of dictionary list values
Sometimes, while working with Python dictionaries, we can have its values as lists. In this can, we can have a problem in that we just require the count of elements in those lists as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let's discuss c
6 min read
Python - Sort list of numbers by sum of their digits
Sorting a list of numbers by the sum of their digits involves ordering the numbers based on the sum of each individual digit within the number. This approach helps prioritize numbers with smaller or larger digit sums, depending on the use case. Using sorted() with a Lambda Functionsorted() function
2 min read