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