Tuesday, November 19, 2024
Google search engine
HomeLanguagesPython program to Sort a List of Dictionaries by the Sum of...

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

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




# Python3 code to demonstrate working of
# Sort Dictionaries by Values Sum
# Using sort() + sum() + values()
 
def values_sum(row):
     
    # return values sum
    return sum(list(row.values()))
 
# initializing list
test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 7, 10 : 1, 3 : 10}, {1 : 100}, {8 : 9, 7 : 3}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# performing sort 
test_list.sort(key = values_sum)
 
# printing result
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




# Python3 code to demonstrate working of
# Sort Dictionaries by Values Sum
# Using sorted() + lambda + sum() + values()
 
# initializing list
test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 7, 10 : 1, 3 : 10}, {1 : 100}, {8 : 9, 7 : 3}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# lambda function to get values sum
res = sorted(test_list, key = lambda row : sum(list(row.values())))
 
# printing result
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:

  1. Initialize a list of dictionaries named “test_list” with four dictionaries inside it.
  2. Create an empty heap list named “heap”.
  3. Iterate through each dictionary in “test_list”.
  4. Compute the sum of values of the current dictionary using the “sum” function and assign it to a variable named “d_sum”.
  5. 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.
  6. The tuple is created by placing “d_sum” first and “d” second.
  7. Create an empty list named “res”.
  8. 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.
  9. Append the dictionary to the “res” list.
  10. Repeat steps 7-8 until there are no more tuples in the “heap” list.
  11. Print the sorted list of dictionaries stored in “res” using the “print” function.

Below is the implementation of the above approach:

Python3




import heapq
 
# initializing list
test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 7, 10 : 1, 3 : 10}, {1 : 100}, {8 : 9, 7 : 3}]
 
# creating an empty heap list
heap = []
 
# iterating through each dictionary and computing the sum of its values
for d in test_list:
    d_sum = sum(d.values())
    # creating a tuple with the dictionary and its sum of values, and adding the tuple to the heap list
    heapq.heappush(heap, (d_sum, d))
 
# creating an empty result list
res = []
 
# popping each tuple from the heap and adding the dictionary to the result list
while heap:
    _, d = heapq.heappop(heap)
    res.append(d)
 
# printing the sorted list of dictionaries
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




# Python3 code to demonstrate working of
# Sort Dictionaries by Values Sum
# Using for loop and dictionary
 
# initializing list
test_list = [{1 : 3, 4 : 5, 3 : 5}, {1 : 7, 10 : 1, 3 : 10}, {1 : 100}, {8 : 9, 7 : 3}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# calculate sum of values and store in dictionary
sum_dict = {}
for d in test_list:
    sum_dict[tuple(d.items())] = sum(d.values())
 
# sort dictionary by value in ascending order
sorted_dict = sorted(sum_dict.items(), key=lambda x: x[1])
 
# initialize empty list to store sorted dictionaries
sorted_list = []
for item in sorted_dict:
    # convert each tuple back to a dictionary
    sorted_list.append(dict(item[0]))
 
# print sorted list of dictionaries
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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments