Python dicton list, maximum value index

I am trying to get a dictionary index with the maximum value of 'size' in a list of dictionaries like the following:

 ld = [{'prop': 'foo', 'size': 100}, {'prop': 'boo', 'size': 200}] 

with the following code I can take the maximum size:

 items = [x['size'] for x in ld] print(max(items)) 

How can I get his index now? Is there an easy way?

Test:

I just decided that I could do this:

 items = [x['size'] for x in ld] max_val = max(items) print(items.index(max_val)) 

it is right?

+12
python dictionary max
source share
2 answers

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.

+18
source share

You can pass the enumerate(ld) function to max with the correct key:

 >>> max(enumerate(ld),key=lambda arg:arg[1]['size'])[0] 1 

If you need a dictionary with the maximum size value, then as a Pythonic approach you can use the operator.itemgetter function as a key:

 In [10]: from operator import itemgetter In [11]: ld = [{'prop': 'foo', 'size': 100}, {'prop': 'boo', 'size': 200}] In [12]: fn = itemgetter('size') In [13]: max(ld, key=fn) Out[13]: {'prop': 'boo', 'size': 200} 
+4
source share

All Articles