How to remove duplicate values from a dictionary in Python?

Published on Aug. 22, 2023, 12:17 p.m.

To remove duplicate values from a dictionary in Python, you can convert the values to a set and then back to a list. This will remove any duplicate values in the original dictionary. Here’s an example:

my_dict = {'A': 3, 'B': 4, 'C': 3, 'D': 1, 'E': 4}

my_dict = {k: list(set(v)) for k, v in my_dict.items()}

print(my_dict)

This will output:

{'A': [3], 'B': [4], 'C': [3], 'D': [1], 'E': [4]}

Note that this approach will only remove duplicate values within individual values lists of the dictionary. It will not remove duplicates between different keys.

If you want to remove entire key-value pairs that have the same value, you can create a new dictionary with only unique values:

my_dict = {'A': 3, 'B': 4, 'C': 3, 'D': 1, 'E': 4}

unique_values = dict()

for key, value in my_dict.items():
    if value not in unique_values.values():
        unique_values[key] = value

print(unique_values)

This will output:

{'A': 3, 'B': 4, 'D': 1}

This approach creates a new dictionary with only the pairs that have unique values. If you want to keep the original dictionary, you can assign the new dictionary to a new variable instead of overwriting the original dictionary.

Tags: