0

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.

abinitio
  • 609
  • 6
  • 20
  • *Sort* the list, then slice off the top 2…?! – deceze May 26 '23 at 13:44
  • There won't necessarily be two at the top. – abinitio May 26 '23 at 13:45
  • 1
    sort the item() of the dictionary by a tuple of the date and the perc. see: [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – JonSG May 26 '23 at 13:45
  • Find the maximum value, then filter the list to all items that have that max value. Or sort the list, then use [`groupby`](https://docs.python.org/3/library/itertools.html#itertools.groupby) to chunk the results by groups and take only the first one. – deceze May 26 '23 at 13:47
  • Sorting the whole list and picking the top k elements is inefficient for large n and small k. I'd look towards [heapq.nlargest](https://docs.python.org/3/library/heapq.html#heapq.nlargest) for that case, but regardless that's not what is being asked here. – tzaman May 26 '23 at 13:48

1 Answers1

2

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

max(managers, key=lambda x:(x['start_date'], x['perc']))
tzaman
  • 46,925
  • 11
  • 90
  • 115