Pythonic way with more than one max possible

Steven D'Aprano steve+comp.lang.python at
Wed Jul 20 06:19:18 CEST 2011

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']
        return values[0]

Assumes that adict has at least two items. May be slow if it has millions of


More information about the Python-list mailing list