Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get max value from a list of dictionaries?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 = -sys.maxsize # This will be a minimum value 
# or you can use: max_high = ohlc[0]['high'] to assign first high value.

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

print(max_high)
#108

If you want to know more about `sys.maxsize’, please see https://www.geeksforgeeks.org/sys-maxsize-in-python/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading