There is a list of dictionaries:

students = [{'name': 'Alex', 'val': 8, 'subj': 'Subj2'}, {'name': 'Natallia', 'val': 10, 'subj': 'Subj2'}, {'name': 'Nikodim', 'val': 10, 'subj': 'Subj2'}] 

Task: Find in this list the maximum value of 'val' with reference to 'name', provided that the objects can have the same value of 'val' - in this case we give all the objects with the same value.

  • What exactly you can not? - Xander

1 answer 1

First we find the maximum val

 In [203]: from operator import itemgetter In [204]: max_val = max(students, key=itemgetter('val'))['val'] 

then we select all elements with maximum val

 In [205]: [x for x in students if x['val'] == max_val] Out[205]: [{'name': 'Natallia', 'subj': 'Subj2', 'val': 10}, {'name': 'Nikodim', 'subj': 'Subj2', 'val': 10}] 

The solution using the Pandas module will most likely work much faster for large amounts of data:

 In [254]: import pandas as pd In [255]: df = pd.DataFrame(students) In [256]: df Out[256]: name subj val 0 Alex Subj2 8 1 Natallia Subj2 10 2 Nikodim Subj2 10 In [257]: df.nlargest(1, columns='val') Out[257]: name subj val 1 Natallia Subj2 10 2 Nikodim Subj2 10 In [258]: df.nlargest(1, columns='val').to_dict('r') Out[258]: [{'name': 'Natallia', 'subj': 'Subj2', 'val': 10}, {'name': 'Nikodim', 'subj': 'Subj2', 'val': 10}] 
  • Cool! Not a trivial decision, but very elegant. - Narnik Gamarnik
  • @NarnikGamarnik, thank you, but it would be cool to do everything in one go through the list - I still can't get it ... - MaxU
  • @MaxU, I just booted up how to do it in one pass, but the solution came only as you basically wrote. For the decision through Pandas, a special thank you, I took it for big data. So, for everyone: if anyone thought about .to_dict ('r') - here’s the description: pandas.pydata.org/pandas-docs/stable/generated/… - MrNinjamannn