How to Remove Duplicates from a Dictionary

79 views

How to Remove Duplicates from a Dictionary

How to Remove Duplicates from a Dictionary

I have a dictionary with duplicate values, and I need to remove these duplicates. How can I do this while preserving the key-value pairs?

solveurit24@gmail.com Changed status to publish February 16, 2025
0

To remove duplicate values from a dictionary, you can iterate over the dictionary items and keep track of values you’ve already seen.

Code Example:

def remove_duplicate_values(d):
    seen = set()
    result = {}
    for key, value in d.items():
        if value not in seen:
            seen.add(value)
            result[key] = value
    return result

# Example usage
original_dict = {"a": 1, "b": 2, "c": 1, "d": 3}
print(remove_duplicate_values(original_dict))  # Output: {"a": 1, "b": 2, "d": 3}

This function iterates through each item in the dictionary, adding values to a set to track duplicates, and builds a new dictionary with unique values.

solveurit24@gmail.com Changed status to publish February 16, 2025
0