Python中获取字典数组内嵌套字典遇TypeError,求解决方案
问题:遍历Topics列表获取actions时报TypeError错误
数据结构示例
返回的Topics列表结构如下:
[ { "Topic Id": null, "Topic Name": null, "Topic Title": null, "Topic Summary": null, "Topic Matching Information": null, "Actions": { "actions": [ { "action_id": "1", "action_title": "Review Video", "action_summary": "Watch the video", "assigned_to": "nomail@email.com", "due_date": "2024-05-24", "action_attachments": [], "action_owner": "Rumble", "action_status": "Open" }, { "action_id": "2", "action_title": "Review Barker Dam Annual Spill", "action_summary": "Read the email about Barker Dam’s Annual Spill Expected in Coming Days.", "assigned_to": "noemail@email.com", "due_date": "2024-05-24", "action_attachments": [], "action_owner": "Your Lower Chautauqua neighbors", "action_status": "Open" } ] } }, { "Topic Id": "new_topic_001", "Topic Name": "G-File Notification", "Topic Title": "G-File Update Notification", "Topic Summary": "Notification about the absence of today's G-File and an update on upcoming content.", "Topic Matching Information": { "subject": "About Today’s G-File", "sender": "", "recipient": "", "keywords": [ "G-File", "newsletter" ] }, "Actions": { "actions": [ { "action_id": "1", "action_title": "Review Today's G-File", "action_summary": "John Smith needs to review the G-File sent on 2024-05-17.", "assigned_to": "John Smith", "due_date": "2024-05-18", "action_attachments": [], "action_owner": "John Smith", "action_status": "None" } ] } } ]
尝试的代码
最初尝试的遍历代码:
for this_topic in topics: for this_action in this_topic["Actions"]["actions"]: # 处理逻辑 pass
还试过以下错误写法:
["Action"].get("actions")(字段名拼写错误,少了末尾的s)["Action"][0](同样拼写错误,且错误将字段视为列表)
错误信息
运行代码后抛出如下错误:
TypeError: list indices must be integers or slices, not str
问题分析
报错提示列表不能使用字符串作为索引,说明在执行this_topic["Actions"]["actions"]时,其中某一层是列表类型而非字典:
- 可能存在部分Topic的
Actions字段不是字典,而是列表(比如接口返回数据格式不一致,部分条目将Actions封装为数组) - 拼写错误:比如尝试
["Action"]而非正确的["Actions"],导致取到None或错误类型,后续操作引发异常
解决方法
方法1:安全取值(推荐)
使用dict.get()方法避免KeyError,同时默认返回空容器,确保遍历不会中断:
for this_topic in topics: # 安全获取Actions字典,无此字段则返回空字典 actions_container = this_topic.get("Actions", {}) # 安全获取actions列表,无此字段则返回空列表 actions_list = actions_container.get("actions", []) for this_action in actions_list: # 处理每个action的逻辑 print(this_action["action_title"])
方法2:类型检查兼容异常格式
如果存在部分Topic的Actions是列表的情况,增加类型判断兼容这种异常格式:
for this_topic in topics: actions_data = this_topic.get("Actions") # 处理Actions是字典的正常情况 if isinstance(actions_data, dict): actions_list = actions_data.get("actions", []) for this_action in actions_list: # 处理逻辑 pass # 处理Actions是列表的异常情况 elif isinstance(actions_data, list): for item in actions_data: actions_list = item.get("actions", []) for this_action in actions_list: # 处理逻辑 pass # 跳过无Actions或格式错误的条目 else: continue
内容的提问来源于stack exchange,提问作者user23640624
相关产品推荐
相关产品推荐

