报错:‘list’对象无‘get’属性,请求排查Python脚本问题
排查AttributeError: 'list' object has no attribute 'get'的问题
这个报错我太熟了,咱们一步步来拆解:
核心原因分析
这个错误的根源很直白:你传入validate_record_schema函数的record变量,某次迭代时不是预期的字典类型,而是列表。而Python的列表(list)压根没有get()方法,所以调用record.get('Payload', {})时直接触发了AttributeError。
结合你的代码来看:
print([validate_record_schema(r) for r in data])
你遍历data列表,把每个元素r当作record传入函数。正常情况下data里的元素应该是像{"Id": "12", "Type": "DevicePropertyChangedEvent"...}这样的字典,但其中至少有一个元素是列表类型,才会导致这个报错。
解决方法
1. 先定位异常数据
给函数加个前置的类型校验,帮你精准找出那条“不对劲”的记录:
def validate_record_schema(record): # 先检查record是否为字典,不是就打印警告并返回False if not isinstance(record, dict): print(f"发现非法记录:类型是{type(record)},内容为{record}") return False device = record.get('Payload', {}) manual_added= device.get('ManualAdded', None) location = device.get('Location', None) if isinstance(manual_added, dict) and isinstance(location, dict): if 'Value' in manual_added and 'Value' in location: return False return isinstance(manual_added, bool) and isinstance(location, str)
运行代码后,控制台会直接打印出那个是列表的异常数据,你就能立刻知道问题出在哪条记录上。
2. 修复数据结构
找到那条异常的列表记录后,把它修正成符合预期的字典结构——毕竟你的函数逻辑是基于“每个record都是包含Payload字段的字典”设计的。
3. 增强函数健壮性(可选)
如果担心后续还会出现类似的非规范数据,可以在函数里层层加校验,比如对device也做类型检查:
def validate_record_schema(record): if not isinstance(record, dict): print(f"发现非法记录:类型是{type(record)},内容为{record}") return False device = record.get('Payload', {}) # 确保device是字典类型,避免后续调用get()出错 if not isinstance(device, dict): print(f"Payload字段不是字典:内容为{device}") return False manual_added= device.get('ManualAdded', None) location = device.get('Location', None) if isinstance(manual_added, dict) and isinstance(location, dict): if 'Value' in manual_added and 'Value' in location: return False return isinstance(manual_added, bool) and isinstance(location, str)
内容的提问来源于stack exchange,提问作者nrs
相关产品推荐
相关产品推荐

