You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

遍历嵌套字典列表匹配author_id,计数结果不符问题排查

问题:统计字典列表中匹配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,未解决问题

解决方案

问题根源

  1. 原代码将每个主字典下的递增计数追加到列表,而非累计总数量
  2. except块逻辑错误:抛出KeyError时subDict可能未定义,且提前return会中断遍历
  3. 未统一累计所有主字典下的匹配条目

修正代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 01:06:21