Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

python - Get max value index for a list of dicts

I'm trying to get the index of the dictionary with the max '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 take its index now? Is there an easy way?

Test:

I just figured I can do this:

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

is this correct?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Tell max() how to calculate the maximum for a sequence of indices:

max(range(len(ld)), key=lambda index: ld[index]['size'])

This'll 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 wanted that dictionary all along, then you could just use:

max(ld, key=lambda d: d['size'])

and to get both the index and the dictionary, you could use enumerate() here:

max(enumerate(ld), key=lambda item: item[1]['size'])

Some more demoing:

>>> 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 each element in the input sequence in turn, and max() will pick the element where the return value of that key function is highest.

Using a separate list to extract all the size values then mapping that back to your original list is not very efficient (you now need to iterate over the list twice). list.index() cannot work as it has to match the whole dictionary, not just one value in it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...