Hi Carlos, On 6/13/07, Carlos <[EMAIL PROTECTED]> 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@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' 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. Kind Regards, Brian Wisti http://coolnamehere.com/ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor