The best solution for receiving dictionary itemes whose value is unique

Question:

Suppose this is the dictionary:

dic = {a: 100, b: 100, c:90}

I would like to get a dictionary with items whose values are unique, In my example this is the result I want to get::

dic_b = {a: 100, c:90}

What will be the best way to do this?

Asked By: Aric a.

||

Answers:

You can inverse the dictionary:

dic = {"a": 100, "b": 100, "c": 90}

dic = {v: k for k, v in {v: k for k, v in dic.items()}.items()}
print(dic)

Prints:

{'b': 100, 'c': 90}

If you want to keep the key of first unique value, you can iterate over the items in reverse:

dic = {"a": 100, "b": 100, "c": 90}

dic = {v: k for k, v in {v: k for k, v in reversed(dic.items())}.items()}
print(dic)

Prints:

{'c': 90, 'a': 100}
Answered By: Andrej Kesely
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.