Get dict from list of dicts with the maximum of two items

Advertisements

I would like to get the dict in a list of dicts which has the maximum of two values:

manager1={"id":"1","start_date":"2019-08-01","perc":20}
manager2={"id":"2","start_date":"2021-08-01","perc":20}
manager3={"id":"3","start_date":"2019-08-01","perc":80}
manager4={"id":"4","start_date":"2021-08-01","perc":80}
managers=[manager1,manager2,manager3,manager4]

I want to select the managers that have the latest start date, then get the manager with the max value of perc

I can do:

max(managers, key=lambda x:x['perc'])

to get the maximum perc, how to i do get it to return more than one dict. In this case it gives manager3. But I want manager4 returned.

>Solution :

You can just create a tuple of your max keys by relevance:

max(managers, key=lambda x:(x['start_date'], x['perc']))

Leave a ReplyCancel reply