Python Practice › Dictionary Programs › Program 94
Sum of unique values across lists
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
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 2
set().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.