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

Python3遍历元组并绘图时遇KeyError问题求助

问题解决思路

核心错误分析

你遇到的KeyError本质是数据结构访问路径错误,结合描述和报错信息,问题出在这几点:

  1. 每个设备的字典中,数据列表存在data字段下,但你的代码直接用data[key]访问,而非先取data['data']
  2. 遍历key_list的逻辑和内部取数逻辑不匹配:循环RSSI和charge (mV)时,却在每个数据点里同时取这两个值,导致逻辑混乱
  3. 尝试data[0]报错是因为data是字典(设备元数据+数据字段),不是列表,不能用索引访问

修正后的代码

根据你的数据结构描述,调整后的代码如下:

import matplotlib.pyplot as plt

key_list = ['RSSI', 'charge (mV)']
fig, axs = plt.subplots(len(key_list))
fig.suptitle('Device Data')

for i, key in enumerate(key_list):
    for device, device_data in teledata.items():
        # 正确获取设备下的data列表,无数据时返回空列表容错
        datapoints = device_data.get('data', [])
        if not datapoints:
            print(f"No data entries for device {device}")
            continue
        
        timeseries = []
        values = []
        try:
            # 遍历每个数据点,提取时间(假设字段为'time',请根据实际替换)和目标key的值
            for dp in datapoints:
                timeseries.append(float(dp['time']))
                values.append(float(dp[key]))
        except KeyError as e:
            print(f"Missing field {e} in device {device}'s data")
        
        axs[i].plot(timeseries, values, label=device)
        axs[i].set_title(key)
        axs[i].set_ylim([0, 100])
        axs[i].legend()  # 添加图例区分不同设备

plt.tight_layout()
plt.show()

关键调整点说明

  • 数据路径修正:用device_data.get('data', [])获取设备下的真实数据列表,避免直接访问字典键导致的KeyError
  • 逻辑匹配:遍历key_list时,每个子图对应绘制该字段随时间的变化,和循环逻辑对齐
  • 容错处理:用get方法和空列表判断,避免无数据时的异常;捕获具体缺失字段的错误,便于调试
  • 可读性优化:添加图例区分不同设备,用tight_layout避免标题重叠

额外调试建议

如果仍有问题,可以先打印设备数据的结构确认:

# 打印第一个设备的结构,查看数据层级
first_device = next(iter(teledata.values()))
print(first_device.keys())
print(first_device['data'][0])  # 打印第一个数据点的键值对,确认字段名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:30:49