[Tutor] Get max quantity

Kent Johnson kent37 at tds.net
Wed Jun 13 20:20:09 CEST 2007


Carlos 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.

In Python 2.5, you can use the key= parameter to max:
In [3]: inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 
'pears': 217}
In [4]: max(inventory, key=inventory.__getitem__)
Out[4]: 'oranges'

In older Pythons, convert the dict to a list of (value, key) pairs and 
find the max of that:

In [5]: max((value, key) for key, value in inventory.iteritems())[1]
Out[5]: 'oranges'

Kent


More information about the Tutor mailing list