遍历嵌套字典列表匹配author_id,计数结果不符问题排查
需求说明
- 遍历字典列表,每个字典包含子字典列表
- 统计所有子字典中
author_id属于mps列表的总条目数(mps包含两个有效author_id) - 主字典的键序列为
['data', 'meta', 'data', 'meta', 'title', 'detail', 'type', 'status']
当前代码
def mp_list6(List, mps): p = [] for mp_dict in List: a=0 try: for subDict in mp_dict["data"]: if subDict["author_id"] in mps: a+=1 p.append(a) except KeyError: if subDict["author_id"] in mps: a=1 p.append(a) return p
现状与期望
- 当前输出为递增整数列表,例如
[1,2,3....94,1,2,3...155,1] - 期望得到匹配条目的总数量(示例中为249)
- 尝试过
defaultdict,未解决问题
解决方案
问题根源
- 原代码将每个主字典下的递增计数追加到列表,而非累计总数量
except块逻辑错误:抛出KeyError时subDict可能未定义,且提前return会中断遍历- 未统一累计所有主字典下的匹配条目
修正代码
def mp_list6(List, mps): total_matches = 0 for mp_dict in List: # 安全获取子字典列表,无"data"键时返回空列表 sub_dicts = mp_dict.get("data", []) for sub_dict in sub_dicts: # 安全获取author_id,避免KeyError author_id = sub_dict.get("author_id") if author_id in mps: total_matches += 1 return total_matches
代码说明
- 用
dict.get()替代直接键访问,避免KeyError,无需额外异常捕获 - 单个变量
total_matches累计所有符合条件的条目数 - 遍历所有主字典和子字典,逻辑简洁直接,最终返回总数量
内容的提问来源于stack exchange,提问作者Benjamin Allen
相关产品推荐
相关产品推荐

