How get a max value from array of dictionaries with the same structure?

I need get a max value of index from dictionary with the biggest index value. I guess this can be done by using function max() and lambda, but I don't know how do it correctly.

 data = [
    {'address': '499 Eastern Parkway',
      'city': 'Kenvil',
      'company': 'GONKLE',
      'country': 'India',
      'index': 0,
      'name': 'Shelby Gutierrez'},
     {'address': '552 Butler Place',
      'city': 'Rivereno',
      'company': 'FITCORE',
      'country': 'United States',
      'index': 1,
      'name': 'Jenny Cardenas'},
     {'address': '176 Pleasant Place',
      'city': 'Coultervillle',
      'company': 'CONFRENZY',
      'country': 'Sao Tome and Principe',
      'index': 2,
      'name': 'Boyer Austin'}
    ]

Upvotes: 0

Views: 28

Answers (2)

Vasilis G.
Vasilis G.

Reputation: 7859

You can try this:

def maxIndex(data):
    return max(d['index'] for d in data)

print(maxIndex(data))

The result is:

2

If you don't want to use loops, you can also do:

def maxIndexWithMap(data):
    return max(list(map(lambda i: i['index'], data)))

print(maxIndexWithMap(data))

The result again is:

2

Upvotes: 1

FredrikHedman
FredrikHedman

Reputation: 1253

If it is just the value you are looking for, then generator expresshon should do it:

max(d['index'] for d in data)

Upvotes: 0

Related Questions