admin管理员组

文章数量:1122832

I have a dictionary in Python where some values are repeated across different keys. I want to remove the key-value pairs with duplicate values while keeping the first occurrence. Here's an example of my dictionary:

my_dict = {
    'a': 1,
    'b': 2,
    'c': 1,
    'd': 3
}

I want the output to be:

{
    'a': 1,
    'b': 2,
    'd': 3
}

How can I achieve this? What is the most efficient way to do this in Python?

I have a dictionary in Python where some values are repeated across different keys. I want to remove the key-value pairs with duplicate values while keeping the first occurrence. Here's an example of my dictionary:

my_dict = {
    'a': 1,
    'b': 2,
    'c': 1,
    'd': 3
}

I want the output to be:

{
    'a': 1,
    'b': 2,
    'd': 3
}

How can I achieve this? What is the most efficient way to do this in Python?

Share Improve this question edited Nov 22, 2024 at 6:19 keepAlive 6,6555 gold badges28 silver badges41 bronze badges asked Nov 22, 2024 at 3:45 Kunal GargKunal Garg 11 bronze badge 1
  • 2 This question is similar to: Removing Duplicates From Dictionary. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – Anerdw Commented Nov 22, 2024 at 4:12
Add a comment  | 

3 Answers 3

Reset to default 1

Since dicts would inherently deduplicate keys, and all the values in your input dict are hashable, you can effectively deduplicate values by making an intermediary dict with values as keys and keys as values. Use the dict.setdefault method to keep only the value of the first occurrence of each distinct key, and then create the final dict from the intermediary dict with key and values swapped back:

my_dict = {'a': 1, 'b': 2, 'c': 1, 'd': 3}
value_keys = {}
for key, value in my_dict.items():
    value_keys.setdefault(value, key)
print(dict(map(reversed, value_keys.items())))

This outputs:

{'a': 1, 'b': 2, 'd': 3}

Demo: https://ideone.com/YQ5WLp

I want to remove the key-value pairs with duplicate values while keeping the first occurrence

  • Using setdefault() method.

No need to builtin map() and reverse().

A simpler method to accomplish this:

Snippet:

my_dict =  {'a': 1, 'b': 2, 'c': 1, 'd': 3} 
res = {}
for key, val in my_dict.items():
    res.setdefault(val, key)

print(dict((v, k) for k, v in res.items()))

Output:

{'a': 1, 'b': 2, 'd': 3}

If you want only the first occurrence of each value be kept, then you can do this:

my_dict = {
    'a': 1,
    'b': 2,
    'c': 1,
    'd': 3
}

seen = set()
result = {k: v for k, v in my_dict.items() if v not in seen and not seen.add(v)}

print(result)

Output:

{'a': 1, 'b': 2, 'd': 3}

The code does the work with a time complexity of O(n)

本文标签: How to ensure a unique set of dictionary values in Python by removing duplicate valuesStack Overflow