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
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 find the highest 3 values in a dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. Examples: Input : my_dict = {'A': 67, 'B': 23, 'C': 45, 'D': 56, 'E': 12, 'F': 69} Output :
5 min read
Python program to check whether the values of a dictionary are in same order as in a list
Given a dictionary, test if values are in order with list values. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub_list = [4, 10, 11] Output : True Explanation : Values are 4, 10, 11, same as list order. Hence True is returned. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub
6 min read
Python program to find the sum of all items in a dictionary
The task of finding the sum of all items in a dictionary in Python involves calculating the total of all values stored in a dictionary. For example, given a dictionary {'a': 100, 'b': 200, 'c': 300}, the sum of values would be 100 + 200 + 300 = 600. Using sum()This is the simplest and fastest method
3 min read
Python | Combine the values of two dictionaries having same key
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Combining dictionaries is very common task in operations
7 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 | 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 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