user266003
user266003

Reputation:

Find maximum value in a list of dictionaries

Given a data structure:

   [
    {'id':0, 'items': 
      [
       {'id': 0,  name: "Tom1", age: 10}, 
       {'id': 0, name: "Mark1", age: 15}, 
       {'id': 0, name: "Pam1", age: 17}
      ]
    },
    {'id':1, 'items': 
      [
       {'id': 1,  name: "Tom12", age: 8}, 
       {'id': 1, name: "Mark12", age: 3}, 
       {'id': 1, name: "Pam12", age: 2}
      ]
    },

    {'id':2, 'items': 
      [
       {'id': 2,  name: "Tom13", age: 55}, 
       {'id': 2, name: "Mark13", age: 66}, 
       {'id': 2, name: "Pam13", age: 77}
      ]
    },
  ]

I want to find an item in each dictionary where age has maximum value and select it. How do I achieve that?

Upvotes: 3

Views: 9389

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

Try this:

for dVals in yourData:
    print max(dVals['items'], key=lambda x:x['age'])

Or one-liner:

print [max(dVals['items'], key=lambda x: x['age']) for dVals in yourData]

{'id': 0, 'age': 17, 'name': 'Pam1'}
{'id': 1, 'age': 8, 'name': 'Tom12'}
{'id': 2, 'age': 77, 'name': 'Pam13'}

Upvotes: 8

Sam Mussmann
Sam Mussmann

Reputation: 5993

def find_largest_age(entry):
  return max(entry['items'], key=lambda d: d['age'])

map(find_largest_age, data_structure)

map will apply the function to each entry in your toplevel list.

max will call the function provided in key on each member of the 'items' list and return the one for which that function gives a maximal value.

Note that you can make this a one-liner:

map(lambda e: max(e['items'], key=lambda d: d['age']), data_structure)

But that's rather more unreadable.

Upvotes: 0

Related Questions