[Tutor] Get max quantity

Jason Massey jason.massey at gmail.com
Wed Jun 13 20:27:58 CEST 2007


More than one way to skin a cat:

>>> import operator
>>> sort_key = operator.itemgetter(1)
>>> sorted(inventory.items(),key=sort_key)[-1]
('oranges',525)

or...

>>> inventory.items()
[('pears', 217), ('apples', 430), ('oranges', 525), ('bananas', 312)]
>>> count_first = [(count,fruit) for fruit,count in inventory.items()]
>>> count_first
[(217, 'pears'), (430, 'apples'), (525, 'oranges'), (312, 'bananas')]
>>> max(count_first)
(525, 'oranges')

And then of course you could iterate over the dictionary setting up
variables that hold the highest fruit and count found so far.



On 6/13/07, Carlos <carloslara at web.de> wrote:
>
> Hello,
>
> If I have a dictionary like:
>
> inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217}
>
> How can I get the item with the largest quantity? I tried:
>
> max(inventory)
>
> but got:
>
> 'pears'
>
> What I would like to get is 'oranges', at least in this case.
>
> Thanks,
> Carlos
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070613/8479aa28/attachment.htm 


More information about the Tutor mailing list