Sort by the sum of list values

EasyDictionary Programs · 91 of 94

Write a Python program to map each key to the sum of its list and sort by that sum.

Advertisement
Input
{"x": [1, 5, 6], "y": [4, 8, 2], "c": [3, 9]}
Output
{'x': 12, 'c': 12, 'y': 14}

Approach

  1. Sum the lists, then sort by value.

Solution

Python
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}
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More dictionary programs

← All 94 Dictionary Programs