Python:带if判断的enumerate循环索引误用及嵌套字典取值方案
问题原因与解决方案
问题原因
你代码里的enumerate(list['sublist'])会返回两个值:index是当前sublist在父数组中的序号,sublist是数组里的单个字典/文档对象。但你错误地用sublist[index]去访问这个对象——sublist的键是字符串(比如item、subListCreator),根本没有数字索引的键,这直接导致了KeyError。
解决方案
方法1:直接遍历子列表元素
去掉多余的enumerate,直接遍历list['sublist']里的每个对象,直接访问其字段即可:
number = None username = None for sublist in list['sublist']: if sublist['item'][0]['commentId'] == commentid: number = sublist['item'][0]['positionId'] username = sublist['subListCreator'] break # 找到匹配项后提前退出,提升效率 print(number) print(username)
方法2:获取完整匹配分支(推荐)
如果需要拿到整个匹配的字典分支,用生成器表达式更简洁:
# 找到第一个匹配的sublist,找不到返回None matched_sublist = next( (s for s in list['sublist'] if s['item'][0]['commentId'] == commentid), None ) if matched_sublist: number = matched_sublist['item'][0]['positionId'] username = matched_sublist['subListCreator'] print(number) print(username) else: print("未找到对应commentId的条目")
注意事项
- 提前初始化
number和username为None,避免循环未找到匹配项时调用print引发未定义变量错误。 - 如果
item数组可能为空,建议增加判断避免IndexError:if sublist.get('item') and sublist['item'][0]['commentId'] == commentid: # 后续逻辑
内容的提问来源于stack exchange,提问作者planetstarbucks
相关产品推荐
相关产品推荐

