2

I have a dictionary (d) with unique keys, however some of the values are not unique. I want to create a dictionary (result) that only contains the unique values. The key associated with the first instance of a unique value in d should be what appears in result.

What is an efficient way to do this?

I've found similar questions with similar data structures that use tuples and sets to eventually arrive at, for example, lists of unique values. I'm unsure how to apply these solutions when I am interested in preserving the original keys and the original data structure.

Any further help would be much appreciated.

d = {
'a': ['1', '1', '0', '0', '0'],
'b': ['0', '1', '0', '0', '0'],
'c': ['0', '1', '0', '0', '0'],
'd': ['1', '1', '0', '0', '0'],
'e': ['0', '1', '0', '0', '0'],
'f': ['0', '1', '0', '0', '1']
}

result = {
'a': ['1', '1', '0', '0', '0'],
'b': ['0', '1', '0', '0', '0'],
'f': ['0', '1', '0', '0', '1']
}
doine
  • 336
  • 1
  • 12

1 Answers1

4

You can do this,

r = {}
for k,v in d.items():
    if not tuple(v) in r.values():
       r[k] = tuple(v)
{k: list(v) for k, v in r.items()}

output:

{'a': ['1', '1', '0', '0', '0'],
 'b': ['0', '1', '0', '0', '0'],
 'f': ['0', '1', '0', '0', '1']}
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • Thank you for this. Does this answer differ to the one given by @mechanic-pig? As far as I can tell, they are identical, though this is easier to follow (for me). – doine Oct 17 '22 at 16:18
  • 1
    mechanic-pig's method is doing dict-comprehension. But the core idea is the same convert to `tuple' and check which already exists. – Rahul K P Oct 17 '22 at 16:21