Python program to sort dictionary by value summation

Python program to sort dictionary by value summation,  In this dictionary program will sort the dictionary data as per the sum of list data in ascending order.

Steps to solve the program

1. Create an empty dictionary temp, temp = {}
2. Iterate over the dictionary key and value with for loop.
    for key, value in input_dict.items()
3. Add the key and sum of values in the temp dictionary.
    temp[key] = sum(value)
4. Sort all the elements of the dictionary using the sorted method.
    which will return the list tuple of key and value pairs. 
    sorted(temp.items(), key=lambda x:x[1])
5. Convert a list of data into a dictionary.
    output = dict(sorted_values)
6. print the output.

				
					input_dict = { "x":[1,5,6], "y":[4,8,2], "c":[3,9] }
temp = {}
for key, value in input_dict.items():
    temp[key] = sum(value)

sorted_values = sorted(temp.items(), key=lambda x:x[1])
output = dict(sorted_values)
print(output)
				
			

Output :

				
					 { x:12, c:12, y:14}
				
			

Invert a given dictionary with non-unique hashable values.

convert a dictionary into n sized dictionary.

Leave a Comment