-2

I have python list of dictionaries as below. I would like to find max value of 'high' field.

ohlc = [
  {
    'open' : 100,
    'high' : 105,
    'low' : 95,
    'close' : 103
  },
  {
    'open' : 102,
    'high' : 108,
    'low' : 101,
    'close' : 105
  }
  {
    'open' : 101,
    'high' : 106,
    'low' : 100,
    'close' : 105
  }
]

In this case function should return high = 108.

martineau
  • 119,623
  • 25
  • 170
  • 301
joenpc npcsolution
  • 737
  • 4
  • 11
  • 25

2 Answers2

2

Use the key parameter to the max function like so:

ohlc = [
  {
    'open' : 100,
    'high' : 105,
    'low' : 95,
    'close' : 103
  },
]
print(max(ohlc, key=(lambda item: item['high'])))
  • FWIW, this could also be written as max(ohlc, key=operator.itemgetter('high'))) which might be faster than using a user-defined `lambda` function if the list has a very large number of dictionaries. – martineau Feb 25 '22 at 21:33
  • Fair enough, TIL about operator.itemgetter – Samarth Ramesh Feb 27 '22 at 01:16
2

I provide a simple and easily understandable way using for loop, as follows:

import sys
ohlc = [
    {
        'open': 100,
        'high': 105,
        'low': 95,
        'close': 103
    },
    {
        'open': 102,
        'high': 108,
        'low': 101,
        'close': 105
    },
    {
        'open': 101,
        'high': 106,
        'low': 100,
        'close': 105
    }
]

max_high = ohlc[0]['high'] to assign first high value.

for i in ohlc[1:]:
    if i['high'] > max_high:
        max_high = i['high']

print(max_high)
#108
Park
  • 2,446
  • 1
  • 16
  • 25