Python Practice › Dictionary Programs › Program 9
Remove duplicate values
Write a Python program to keep only the first key for each distinct value.
Input
{"a": 12, "b": 2, "c": 12, "d": 5, "e": 35, "f": 5}Output
{'a': 12, 'b': 2, 'd': 5, 'e': 35}Approach
- Remember the values seen while copying items.
Solution
d = {"a": 12, "b": 2, "c": 12, "d": 5, "e": 35, "f": 5}seen = set()result = {}for k, v in d.items(): if v not in seen: seen.add(v) result[k] = vprint(result)Output
{'a': 12, 'b': 2, 'd': 5, 'e': 35}Learn the concept
New to this topic? Read the lesson, then come back.