循环报错list indices must be integers or slices, not dict,求代码修复方法
问题解决:list indices must be integers or slices, not dict 报错处理
问题根源
- 类型不匹配报错:
h['RawAQData']['Data']返回的是列表,但你把它当成字典来遍历,用hv[k]访问元素——列表只能用整数索引或切片,不能用字典对象当索引,这就是报错的直接原因。 - 未定义变量问题:代码里
max_key = key中的key是未声明的变量,运行到这里还会触发NameError。
修正后的代码
假设API返回的Data列表中,每个元素是包含键值对的字典(比如每个字典有"Key"和"Value"字段,需根据实际API返回调整),修正代码如下:
def highest_value(): """返回最高值对应的键""" h = get_live_data_from_api('MY1', 'NO') data_list = h['RawAQData']['Data'] highest_number = None max_key = None for item in data_list: # 替换为API返回字典中存储数值的真实键名,比如"Value" current_value = item.get("Value") # 跳过非数值类型的元素,避免报错 if not isinstance(current_value, (int, float)): continue if highest_number is None or current_value > highest_number: highest_number = current_value # 替换为API返回字典中存储目标键的真实键名,比如"Key" max_key = item.get("Key") return max_key print(highest_value())
关键调整说明
- 遍历列表时直接取每个元素(
item),而不是把元素当索引用。 - 用
item.get("键名")安全获取字典中的值,避免键不存在引发KeyError。 - 增加了数值类型判断,过滤掉非数值元素,防止比较时出错。
- 如果你不确定API返回的具体结构,先加一行
print(data_list)打印输出,明确每个字典的键名后再替换代码中的"Value"和"Key"。
内容的提问来源于stack exchange,提问作者Zengag
相关产品推荐
相关产品推荐

