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

如何遍历嵌套字典提取含特定键‘fruit’的子字典键值并生成DataFrame

实现方法

核心思路

遍历所有嵌套字典的子节点,筛选出包含fruit键的子字典,汇总后直接生成DataFrame即可,pandas会自动匹配你需要的三个字段,多余字段会自动忽略。

完整可运行代码

import pandas as pd

# 待处理的嵌套字典集合,可自行新增更多字典到列表中
raw_dicts = [
    {'A':{'color':'red','price':22, 'fruit':'apple'},'B':{'color':'orange','price':123, 'vegetable':'carrot'}},
    {'X':{'color':'yellow','price':2, 'fruit':'banana'},'Y':{'color':'yellow','price':14, 'vegetable':'melon'}}
]

valid_records = []
# 遍历所有顶层字典
for item in raw_dicts:
    # 遍历每个顶层字典下的所有子字典
    for sub_dict in item.values():
        # 只保留包含fruit键的子字典
        if "fruit" in sub_dict:
            valid_records.append(sub_dict)

# 生成指定列的DataFrame
df = pd.DataFrame(valid_records, columns=["color", "price", "fruit"])

输出结果

打印df会得到如下格式的内容:

color  price   fruit
0     red     22   apple
1  yellow      2  banana

可选扩展

如果需要保留顶层字典的键名(比如示例中的A、X),可以修改遍历逻辑,把顶层键加入子字典后再汇总:

valid_records = []
for item in raw_dicts:
    for top_key, sub_dict in item.items():
        if "fruit" in sub_dict:
            sub_dict["top_key"] = top_key
            valid_records.append(sub_dict)
# 生成DataFrame时把top_key加入columns参数即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:24:03