How to create a dictionary with only the unique values and associated keys of another dictionary?

Question:

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']
}
Asked By: fangfoss

||

Answers:

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']}
Answered By: Rahul K P
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.