[Tutor] Get max quantity

Kent Johnson kent37 at tds.net
Thu Jun 14 20:47:26 CEST 2007


Brian Wisti wrote:
> Hi Carlos,
> 
> 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
>>
> 
> There are indeed several ways to sort this particular cat. Here's my
> own favorite:
> 
> # Sort the list of keys by inventory count, from high to low
>>>> inventory
> {'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 312}
>>>> items = inventory.keys()
>>>> items
> ['pears', 'apples', 'oranges', 'bananas']
>>>> items.sort(cmp=lambda a,b: cmp(inventory[b], inventory[a]))
>>>> items
> ['oranges', 'apples', 'bananas', 'pears']
>>>> items[0]
> 'oranges'

You should learn how to use the key parameter to sort, it is much more 
efficient than using cmp and IMO easier to write and understand. In this 
case, you could use key=inventory.__getitem__

> 
> It does result in another list, same as the the approaches listed by
> Kent and Jason. If *all* you were interested was the key associated
> with the greatest inventory count, you could wrap your favorite
> solution in a function and return the key from that.

Neither of my original suggestions created another list. This is 
actually a significant difference between my solutions using max() and 
yours and Jason's using sort. If the list is long using max() could be 
much more efficient because it just makes a single pass through the 
list. max() has O(n) complexity whereas in general sort is O(n log n) so 
as n gets large the advantage of max() should increase. Also for large n 
there should be an advantage to not creating the intermediate list.

As always, if you care about the time taken by an operation, measure 
(with timeit); I am just making educated guesses.

Kent
> 
> Kind Regards,
> 
> Brian Wisti
> http://coolnamehere.com/
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list