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']
}
CodePudding user response:
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']}