You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

访问字典值内嵌套列表,筛选Meraki API返回的lossPercent大于5.00的数据

代码调整说明

你原有代码的核心问题是对timeSeries的类型判断错误,同时缺少None值校验,调整点如下:

  • 修复timeSeries遍历逻辑:timeSeries是列表类型,直接遍历元素即可,无需调用.values方法
  • 新增lossPercent空值校验:比较数值前先确认字段不为None,避免类型报错
  • 优化文件操作逻辑:使用with上下文管理器管理文件句柄,无需手动关闭文件,更稳定
  • 调整异常捕获范围:提前捕获外层字段缺失异常,避免无意义的后续操作
import requests
import json

response = requests.request('GET', dev_status, headers=headers, data=payload)
response_data = json.loads(response.text)

for item in response_data:
    # 提前读取外层通用字段,捕获缺失异常
    try:
        serial = item['serial']
        uplink = item['uplink']
        ip = item['ip']
        time_series = item['timeSeries']
    except KeyError:
        continue
    
    # 遍历时间序列节点
    for ts_node in time_series:
        loss_percent = ts_node.get('lossPercent')
        # 排除空值后做数值比较
        if loss_percent is not None and loss_percent > 5.0:
            # 符合条件写入文件
            with open("PL.txt", "a", encoding="utf-8") as f:
                print(f"Serial:{serial}", file=f)
                print(f"Uplink:{uplink}", file=f)
                print(f"IP:{ip}", file=f)
                print(f"匹配的时间序列节点:{ts_node}", file=f)
                print("\n", file=f)

若需求为只要存在任意一个符合条件的时间序列节点,就存储该设备的完整timeSeries数据,只需在判断条件成立后修改打印内容为完整time_series变量,再添加break跳出内层循环即可。

内容的提问来源于stack exchange,提问作者moehawk__

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 14:06:04