-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
  • 112,593
  • 23
  • 157
  • 280
joenpc npcsolution
  • 631
  • 3
  • 9
  • 20
  • 1
    What did you try? – Shaida Muhammad Feb 25 '22 at 03:35
  • What attempt have you made? Contrary to what you seem to think, StackOverflow is not a free coding service. You're expected to make an [honest attempt at the solution](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – martineau Feb 25 '22 at 03:38

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
  • 1,924
  • 1
  • 15
  • 19