0

I have this list

result = [{"name": "A", "score": 35, "other_details": ""},
          {"name": "A", "score": 60,"other_details": ""},
          {"name": "B", "score": 45, "other_details": ""}, 
          {"name": "B", "score": 34, "other_details": ""},
          {"name":"C", "score": 65, "other_details": ""}]

Now, I want to get the whole dictionary on the basis of maximum score for each name.

My expected output is:

[{"name": "A", "score": 60,"other_details": ""}]

[{"name": "B", "score": 45, "other_details": ""}]

[{"name":"C", "score": 65, "other_details": ""}]
Rakesh
  • 81,458
  • 17
  • 76
  • 113

1 Answers1

0

Using itertools.groupby

Ex:

from itertools import groupby

result = [{"name": "A", "score": 35, "other_details": ""},
          {"name": "A", "score": 60,"other_details": ""},
          {"name": "B", "score": 45, "other_details": ""}, 
          {"name": "B", "score": 34, "other_details": ""},
          {"name":"C", "score": 65, "other_details": ""}]

data_result = [max(list(v), key=lambda x: x["score"]) for k, v in groupby(sorted(result, key=lambda x: x["name"]), lambda x: x["name"])]
print(data_result)

Output:

[{'name': 'A', 'other_details': '', 'score': 60},
 {'name': 'B', 'other_details': '', 'score': 45},
 {'name': 'C', 'other_details': '', 'score': 65}]
Rakesh
  • 81,458
  • 17
  • 76
  • 113