I am trying to retrieve the sublist with a maximum key value inside a list.
eg. In this example, I am trying to retrieve the sublist with maximum confidence score:
listA=[{'id': '1', 'actions': [{'acc': 'ac1', 'coordinates': [569, 617, 627, 631], 'confidence': 93.0}]}, {'id': '1', 'actions': [{'acc': 'acc1','coordinates': [569, 617, 627, 631], 'confidence': 94.0}]}, {'id': '1', 'actions': [{'acc': 'acc1', 'coordinates': [569, 617, 627, 631], 'confidence': 95.0}]}]
The expected output is :
[{'id': '1', 'actions': [{'acc': 'acc1', 'coordinates': [569, 617, 627, 631], 'confidence': 95.0}]
I have used itemgetter but it is not returning the desired output.
I've used python's max function and provided it with a key that will use the confidence key-value as the way to find the maximum.
listA=[{'id': '1', 'actions': [{'acc': 'ac1', 'coordinates': [569, 617, 627, 631], 'confidence': 93.0}]},
{'id': '1', 'actions': [{'acc': 'acc1','coordinates': [569, 617, 627, 631], 'confidence': 94.0}]},
{'id': '1', 'actions': [{'acc': 'acc1', 'coordinates': [569, 617, 627, 631], 'confidence': 95.0}]}]
maxList = max(listA, key=lambda x: x['actions'][0]['confidence'])
print(maxList)
You could do almost exactly the same thing if you wanted to return a sorted list of the items rather than just the maximum. You'd just replace max
with sorted
EDIT: Thanks @tobias_k for the great suggestion. If there is more than one action, replace the lambda with lambda x: max(a['confidence'] for a in x['actions'])