Python Practice › Dictionary Programs › Program 91
Sort by the sum of list values
Write a Python program to map each key to the sum of its list and sort by that sum.
Input
{"x": [1, 5, 6], "y": [4, 8, 2], "c": [3, 9]}Output
{'x': 12, 'c': 12, 'y': 14}Approach
- Sum the lists, then sort by value.
Solution
d = {"x": [1, 5, 6], "y": [4, 8, 2], "c": [3, 9]}sums = {k: sum(v) for k, v in d.items()}print(dict(sorted(sums.items(), key=lambda kv: kv[1])))Output
{'x': 12, 'c': 12, 'y': 14}Learn the concept
New to this topic? Read the lesson, then come back.