Pythonic way with more than one max possible
Thomas Jollans
t at jollybox.de
Wed Jul 20 06:51:39 EDT 2011
On 20/07/11 06:19, Steven D'Aprano wrote:
> On Wed, 20 Jul 2011 01:17 pm CM wrote:
>
>> I have three items in a dict, like this:
>>
>> the_dict = {'a':1, 'b':2, 'c':3}
>>
>> but the vals could be anything. I want to configure something else
>> based on the "winner" of such a dict, with these rules:
>>
>> 1. In this dict, if there is a UNIQUE max value, that's the winner.
>> 2. If there are any TIES for max value, b is the winner by default.
>>
>> The problem for me, as I see it, is I don't know any elegant ways to
>> do this in Python. The max(dict) function doesn't distinguish between
>> unique and non-unique maxes. I could go through and test the various
>> possibilities (to see if the max value had any matches in the other
>> values), but, knowing Python, there is probably something close to
>> "one way to do it". Any suggestions?
>
> # Untested.
> def get_winner(adict):
> values = sorted(adict.values(), reverse=True)
> if values[0] == values[1]:
> return adict['b']
> else:
> return values[0]
# Untested, with keys:
def get_winner(adict):
values = sorted(adict.items(), reverse=True,
key=(lambda k_v: k_v[1]))
if values[0][1] == values[1][1]:
return 'b'
else:
return values[0][0]
>
> Assumes that adict has at least two items. May be slow if it has millions of
> items.
>
>
More information about the Python-list
mailing list