Pythonic way with more than one max possible

Chris Rebert clp2 at rebertia.com
Wed Jul 20 00:33:18 EDT 2011


On Tue, Jul 19, 2011 at 8:17 PM, CM <cmpython at gmail.com> 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.

Er, for (2), you mean b's /value/ is the winner, right?

> 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?

# presumes at least 2 items
from heapq import nlargest
winner, runner_up = nlargest(2, the_dict.itervalues())
if winner == runner_up:
    winner = the_dict['b']

Cheers,
Chris
--
http://rebertia.com



More information about the Python-list mailing list