Search code examples
pythonpython-itertools

Best pythonic way to find the max value in a matrix of objects


I have the following code:

resdata = dict()
rows = result.rows.all()
for key, group in groupby(rows, lambda x: x.space):
    row = list()
    for item in group:
        cell = {
            'time': item.time,
            'value': item.value
        }
        row.append(cell)
    resdata[key] = row

a sample resdata would be:

    resdata = [
    {
      "skl": "nn_skl:5608", 
      "cols": [
        {
          "value": 115.396956868, 
          "time": "2012-06-02 00:00:00"
        }, 
        {
          "value": 112.501399874, 
          "time": "2012-06-03 00:00:00"
        }, 
        {
          "value": 106.528068506, 
          "time": "2012-06-18 00:00:00"
        }
      ], 
      "len": 226
    }, 
    {
      "skl": "nn_skl:5609", 
      "cols": [
        {
          "value": 114.541167284, 
          "time": "2012-06-02 00:00:00"
        }, 
      ], 
      "len": 226
    }, 
    {
      "skl": "nn_skl:5610", 
      "cols": [
        {
          "value": 105.887267189, 
          "time": "2012-06-18 00:00:00"
        }
      ], 
      "len": 225
    }
]

What I want to do is to get the maximum 'value' and the maximum 'time' among all the cells.


Solution

  • Assuming you've converted into a Python object with json.loads or whatnot, then you want something like:

    max(b["time"] for b in a["cols"] for a in data)