Tell max() how to calculate the maximum for a sequence of indices:
max(range(len(ld)), key=lambda index: ld[index]['size'])
This will return the index for which the size key is the highest:
>>> ld = [{'prop': 'foo', 'size': 100}, {'prop': 'boo', 'size': 200}] >>> max(range(len(ld)), key=lambda index: ld[index]['size']) 1 >>> ld[1] {'size': 200, 'prop': 'boo'}
If you always wanted this dictionary, you can simply use:
max(ld, key=lambda d: d['size'])
and to get the index and dictionary, you can use enumerate() here:
max(enumerate(ld), key=lambda item: item[1]['size'])
A little more demo:
>>> max(ld, key=lambda d: d['size']) {'size': 200, 'prop': 'boo'} >>> max(enumerate(ld), key=lambda item: item[1]['size']) (1, {'size': 200, 'prop': 'boo'})
The key function is passed to each element of the input sequence in turn, and max() will select the element whose key return value is the highest.
Using a separate list to retrieve all size values ββand then matching it with the original list is not very efficient (now you need to iterate through the list twice). list.index() cannot work, because it must match the entire dictionary, and not just the single value in it.
Martijn pieters
source share