This is a similar idea to @AxelPuig's solution. But, instead of relying on an auxiliary dictionary each time you wish to retrieve an item with max
or min
value, you can perform a single sort and utilise collections.OrderedDict
:
from collections import OrderedDict
d = {'a' : 5, 'b' : 1, 'c' : 5 }
d_preference1 = {'a': 1, 'b': 2, 'c': 3}
d_preference2 = {'a': 3, 'b': 2, 'c': 1}
d1 = OrderedDict(sorted(d.items(), key=lambda x: -d_preference1[x[0]]))
d2 = OrderedDict(sorted(d.items(), key=lambda x: -d_preference2[x[0]]))
max(d1, key=d.get) # c
max(d2, key=d.get) # a
Since OrderedDict
is a subclass of dict
, there's generally no need to convert to a regular dict
. If you are using Python 3.7+, you can use the regular dict
constructor, since dictionaries are insertion ordered.
As noted on the docs for max
:
If multiple items are maximal, the function returns the first one
encountered.