【问题标题】:Access a list nested inside a dictionary value访问嵌套在字典值中的列表
【发布时间】:2021-11-25 20:22:01
【问题描述】:

我收到以下针对 GET 请求的 Meraki API 回复

[
    {
        "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
            }
        ]
    }
]

或

[
    {
        "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 是一个键,它采用浮点数或布尔值并嵌套在字典中的列表中

我正在尝试编写代码以在 response_data 中找到 lossPercent value> 5.00 并运行:

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

我不知道如何继续

【问题讨论】:

  • for p in response_data[i]['timeSeries']: if p['lossPercent'] > 5:
  • 你按照代码格式化了吗?显然我不能在整个 cmets 中做到这一点。
  • if p['lossPercent'] > 5: TypeError: '>' 在 'NoneType' 和 'int' 的实例之间不支持
  • 没错。 所有您的示例数据都是无类型的。您没有给出大于 5 的数字示例 + 它们都不是浮点数或布尔值
  • 你可以这样做:if isinstance(p['lossPercent'], float): if p['lossPercent'] > 5: ...

标签: python python-3.x meraki-api


【解决方案1】:

您可以直接在 response_data 上使用 for 循环(无需使用索引)。由于时间序列中可能有多个 lossPercent,因此您需要使用 any() 函数来检查其中任何一个是否大于您的 5.00 阈值。

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)

【讨论】:

  • 我刚刚查看了输出,它返回的值小于 5: if any(ts.get('lossPercent') or 0
  • 它需要在(ts.get('lossPercent') or 0) 周围加上括号,我的错。现在修好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-12
  • 1970-01-01
  • 2012-07-26
  • 1970-01-01
  • 2020-10-01
相关资源
最近更新 更多