Reputation: 63
I have the following dictonary:
inventory = {'apple':(3, 133), 'banana':(9, 407), 'pear':(17, 205), 'orange':(1, 91)}
I would like to find key, value pair according to max value of the second element in the tuple so in this case it should return: banana':(9, 407)
I know I can get this result using lambda
:
key_max = max(inventory.keys(), key=(lambda k: inventory[k][1]))
print key_max, inventory[key_max]
However I try to receive same result using itemgetter() method as I read it is faster but I can only get data according to the value of first element of the tuple:
from operator import itemgetter
print max(inventory.iteritems(), key = itemgetter(1))
Is there a way I could get same result using itemgetter()
method?
Upvotes: 1
Views: 283
Reputation: 16782
Before I or someone else comes up with something fascinating:
inventory = {'apple':(3, 133), 'banana':(9, 407), 'pear':(17, 205), 'orange':(1, 91)}
maxVal = 0 # to get the max of 2nd elem from tuple
for k,v in inventory.items():
maxVal = max(maxVal, v[1])
for k,v in inventory.items():
if v[1] == maxVal: # if the 2nd elem of tuple eqs to the maxVal
print(k, v)
OUTPUT:
banana (9, 407)
Note: I recommend the Edited version.
EDIT
Using lambda
:
print(max(inventory.items(), key=lambda x: x[1][1])) # ('banana', (9, 407))
Upvotes: 2
Reputation: 15035
Although I don't see the point of this exercise...
Here's a solution using only itemgetter
and no lambdas, as was the original question:
key = max(zip(inventory.keys(), map(itemgetter(1), inventory.values())), key=itemgetter(1))[0]
print(key, inventory[key])
# banana (9, 407)
Note that the above will only be efficient in Python 3.x where the built-in functions return iterators / view objects instead of lists.
An equally efficient Python 2.x equivalent requires the use of library functions such as itertools.izip
:
# from itertools import izip, imap
key = max(izip(inventory.iterkeys(), imap(itemgetter(1), inventory.itervalues())), key=itemgetter(1))[0]
print key, inventory[key]
Upvotes: 2