Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #9942

Re: Pythonic way with more than one max possible

References <acfc6e53-fd3c-4404-9314-aa01dc35c0d7@a31g2000vbt.googlegroups.com> <6e96527b-e41c-4f1a-b829-a2fa7648eaa3@t9g2000vbs.googlegroups.com>
Date 2011-07-19 23:56 -0700
Subject Re: Pythonic way with more than one max possible
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.1280.1311145014.1164.python-list@python.org> (permalink)

Show all headers | View raw


On Tue, Jul 19, 2011 at 10:10 PM, CM <cmpython@gmail.com> wrote:
> On Jul 19, 11:17 pm, CM <cmpyt...@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:
<snip>
> I realize, now though, (and Chris asked about this) that I was
> imprecise in my
> rules.  They really should be stated as:
>
> 1. In this dict, if there is a UNIQUE max value, then its *key* is the
> winner.
> 2. If there are any TIES for max value, then the *key* 'b' is the
> winner by default.
>
> The point is, I am trying to determine the name of the winning
> category, either
> 'a', 'b', or 'c', not the value of its winning score.
>
> So in your solutions there is sorting by values, which makes sense.
> But how
> can I go back to keys from there?  Sorry for the mistake (but even so,
> I learned
> something already).

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

Cheers,
Chris

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-19 20:17 -0700
  Re: Pythonic way with more than one max possible Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-20 14:19 +1000
    Re: Pythonic way with more than one max possible Thomas Jollans <t@jollybox.de> - 2011-07-20 12:51 +0200
  Re: Pythonic way with more than one max possible Chris Rebert <clp2@rebertia.com> - 2011-07-19 21:33 -0700
  Re: Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-19 22:10 -0700
    Re: Pythonic way with more than one max possible woooee <woooee@gmail.com> - 2011-07-19 22:37 -0700
    Re: Pythonic way with more than one max possible Chris Rebert <clp2@rebertia.com> - 2011-07-19 23:56 -0700
  Re: Pythonic way with more than one max possible CM <cmpython@gmail.com> - 2011-07-20 13:25 -0700

csiph-web