Florent
Florent

Reputation: 1928

How to select the dictionary with the highest value in Python?

I have a list of several dictionaries with the same keys and I would like to select the one with the highest value for a specific key. Values are number, how can i do that?

For example, when the specific key is a I would like to select stats[0] as 1000 is greater than 10.

stats = [{'a':1000, 'b':3000, 'c': 100}, {'a':10, 'b':200, 'c': 1}]

Upvotes: 0

Views: 66

Answers (2)

EEAH
EEAH

Reputation: 747

You can use this function:

def select_max (dict, key):
   max = dict[0][key]
   maxElement = dict[0]

   for element in dict:
       if element[key] > max:
           maxElement = element
           max = element[key]

   return maxElement

Input:

select_max([{'a':1000, 'b':3000, 'c': 100}, {'a':10, 'b':200, 'c': 1}],'a')

Output:

{'a': 1000, 'b': 3000, 'c': 100}

Upvotes: 0

Samwise
Samwise

Reputation: 71454

Use max with a key function that selects a:

max(stats, key=lambda d: d['a'])

Upvotes: 6

Related Questions