Sum of unique values across lists
EasyDictionary Programs · 94 of 94
Write a Python program to add up the distinct numbers found in all list values.
Input{"a": [6, 7, 2, 8, 1], "b": [2, 3, 1, 6, 8, 10], "d": [1, 8, 2, 6, 9]} Output[1, 2, 3, 6, 7, 8, 9, 10] 46
Approach
- Union of all values in a set, then sum.
Solution
Python
d = {"a": [6, 7, 2, 8, 1], "b": [2, 3, 1, 6, 8, 10], "d": [1, 8, 2, 6, 9]}unique = set().union(*d.values())print(sorted(unique), sum(unique))
Output
[1, 2, 3, 6, 7, 8, 9, 10] 46
Line by line
Line 2set().union(*lists) merges all the lists into one set of distinct numbers.
Learn the concept
New to this topic? Read the lesson, then come back.
More dictionary programs
← All 94 Dictionary Programs