Access a list nested inside a dictionary value

46 views Asked by At

I have the following Meraki API reply for a GET request

[
    {
        "networkId": "N_12345",
        "serial": "Q2AB-CDEF-GHIJ",
        "uplink": "wan1",
        "ip": "8.8.8.8",
        "timeSeries": [
            {
                "ts": "2019-01-31T18:46:13Z",
                "lossPercent": 5.3,
                "latencyMs": 194.9
            }
        ]
    }
]

or

[
    {
        "networkId": "N_12345",
        "serial": "Q2AB-CDEF-GHIJ",
        "uplink": "wan1",
        "ip": "8.8.8.8",
        "timeSeries": [
            {
                "ts": "2019-01-31T18:46:13Z",
                "lossPercent": None,
                "latencyMs": 194.9
            }
        ]
    }
]

lossPercent is a key that takes a float or a bool value and is nested inside a list in a dictionary

I am trying to write a code to find lossPercent value> 5.00 in response_data and run:

import requests    
response = requests.request('GET', dev_status, headers=headers, data = payload)
response_data = json.loads(response.text)
    
    for i in range(len(response_data)):
        for p in response_data[i]['timeSeries'].values: # This is where I am stuck
            if p >5:
                try:
                    f = open("PL.txt", "a")
                    print("Serial:" + str(response_data[i]['serial']), file=f)
                    print("Uplink" + str(response_data[i]['uplink']), file=f)
                    print("IP:" + str(response_data[i]['ip']), file=f)
                    print("Time Series:" + str(response_data[i]['timeSeries']), file=f)
                    print('\n', file=f)
                    f.close()
                except KeyError:
                    continue

I am not sure how to proceed

1

There are 1 answers

2
Alain T. On

You can use the for-loop directly on response_data (no need to use indexes). Since there may be several lossPercent in the time series, you'll want to use the any() function to check if any of them is larger than your 5.00 threshold.

for endpoint in response_data:
    if any((ts.get('lossPercent') or 0) > 5 for ts in endpoint.get('timeSeries',{})):
       with open("PL.txt", "a") as f:
           print("Serial:", endpoint.get('serial')), file=f)
           print("Uplink",endpoint.get('uplink')), file=f)
           print("IP:",endpoint.get('ip')), file=f)
           print("Time Series:",endpoint.get('timeSeries')), file=f)
           print('\n', file=f)