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

如何用Python从复杂嵌套字典列表中提取指定键值对?

问题:从嵌套字典列表中提取特定键值对

给定如下嵌套字典列表结构的复杂数据:

complex_data = [
    [{'A': 'test1'}, 
     {'A': 'test2'}, 
     {'B': [{'C': {'testabc': {'A': 'xxx'}}}, 
            {'C': {'test123': {'A': 'yyy'}, 'test456': {'A': '111abc'}}}, 
            {'C': {'test123': {'A': 'yyy'}, 'test456': {'A': '111def'}}}]}],
    # ... 其他类似子列表
    [{'A': 'test11'}, 
     {'A': 'test22'}],
    # ... 其他类似子列表
    [{'A': 'test33'}, 
     {'A': 'test44'}, 
     {'B': []}],
    # ... 其他类似子列表
    [{'A': 'test3'}, 
     {'A': 'test4'}, 
     {'B': [{'C': {'testabc': {'A': '111'}}}, 
            {'C': {'test123': {'A': 'yyy'}, 'test456': {'A': '999abc'}}}, 
            {'C': {'test123': {'A': 'yyy'}, 'test456': {'A': '999def'}}}]}]
]

需要提取得到如下嵌套列表结构:

desired_output = [
    [{'A': 'test1'}, {'A': 'test2'}, {'test456': {'A': '111def'}}],
    # ... 其他对应子列表
    [{'A': 'test3'}, {'A': 'test4'}, {'test456': {'A': '999def'}}]
]

原编写的代码无法正常运行:

desired_output = []
for y in complex_data:
    desired_output.append([y[2]['B'][2]['C'] for y in row] for row in y)

问题原因分析

  • 变量命名冲突:外层循环用了y,内层列表推导又用y作为迭代变量,导致变量被覆盖,逻辑完全混乱。
  • 索引越界风险:直接使用固定索引y[2],但部分子列表可能只有前两个元素(没有第三个带B的字典),会触发IndexError。
  • 未处理边界情况:没有考虑B列表为空、B键缺失的场景,直接访问['B'][2]会导致KeyError或IndexError。
  • 生成器误用:内层的(...) for row in y是生成器表达式,不是列表,会导致desired_output里存的是生成器对象而非实际数据。

解决方法

以下代码会处理所有边界情况(B缺失、B为空、B长度不足3),并正确提取目标数据:

desired_output = []

for sublist in complex_data:
    # 先收集前两个元素({'A': ...}的字典)
    result = sublist[:2].copy()
    
    # 检查是否存在第三个元素且包含'B'键
    if len(sublist) >= 3 and 'B' in sublist[2]:
        b_list = sublist[2]['B']
        # 检查B列表长度是否足够取第三个元素(索引2)
        if len(b_list) >= 3:
            c_dict = b_list[2]['C']
            # 提取'test456'对应的键值对,构造成新字典加入结果
            if 'test456' in c_dict:
                result.append({'test456': c_dict['test456']})
    
    desired_output.append(result)

代码说明

  1. 收集固定元素:直接复制子列表的前两个元素,确保基础数据正确。
  2. 安全检查边界:依次检查子列表长度、B键是否存在、B列表长度是否足够、test456键是否存在,避免各种异常。
  3. 构造目标字典:提取test456对应的键值对,以字典形式加入结果列表,保证输出格式符合要求。

运行上述代码后,对于各种场景的输出如下:

  • 有完整B结构的子列表:会正确提取test456对应的字典加入结果。
  • 没有B的子列表:结果仅包含前两个{'A': ...}字典。
  • B为空列表的子列表:结果仅包含前两个{'A': ...}字典。
  • B列表长度不足3的子列表:不会添加额外元素,仅保留前两个字典。

内容的提问来源于stack exchange,提问作者Preeti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:01:06