Remove duplicate values

EasyDictionary Programs · 9 of 94

Write a Python program to keep only the first key for each distinct value.

Advertisement
Input
{"a": 12, "b": 2, "c": 12, "d": 5, "e": 35, "f": 5}
Output
{'a': 12, 'b': 2, 'd': 5, 'e': 35}

Approach

  1. Remember the values seen while copying items.

Solution

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

Learn the concept

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

More dictionary programs

← All 94 Dictionary Programs