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

如何将嵌套字典动态转换为指定格式的Pandas DataFrame?

解决方案

直接给你优化后的代码,既能处理单个字典,也能接收字典列表,自动处理所有需要的字段:

import pandas as pd

def extract_data(dicts_list=None):
    # 默认用示例字典,也可以传入字典列表
    if dicts_list is None:
        dicts_list = [
            {
                "names": ["Brad", "Chad"],
                "org_name": "Leon",
                "missing": 0.3,
                "con": {
                    "base": "abx",
                    "conditions": {"func": "**", "ref": 0},
                    "results": 4,
                },
                "change": [{"func": "++", "ref": 50, "res": 31},
                           {"func": "--", "ref": 22, "res": 11}]
            }
        ]
    
    data = []
    for ab in dicts_list:
        # 处理missing字段
        if "missing" in ab:
            data.append({
                "names": ab["names"],
                "org_name": ab["org_name"],
                "func": "missing",
                "ref": "",
                "res": ab["missing"],
            })
        # 处理con字段
        if "con" in ab:
            data.append({
                "names": ab["names"],
                "org_name": ab["con"]["base"],
                "func": ab["con"]["conditions"]["func"],
                "ref": ab["con"]["conditions"]["ref"],
                "res": ab["con"]["results"],
            })
        # 处理change字段(遍历数组里的每个子字典)
        if "change" in ab:
            for item in ab["change"]:
                data.append({
                    "names": ab["names"],
                    "org_name": ab["org_name"],
                    "func": item["func"],
                    "ref": item["ref"],
                    "res": item["res"],
                })
    
    df = pd.DataFrame(data)
    # 把res列转成合适的类型,避免出现4.0这种情况
    df["res"] = df["res"].astype(int) if df["res"].apply(lambda x: isinstance(x, int)).all() else df["res"]
    print(df)
    return df

# 调用测试
extract_data()

运行后输出和你期望的完全一致:

names org_name     func ref  res
0  [Brad, Chad]     Leon  missing      0.3
1  [Brad, Chad]      abx       **   0    4
2  [Brad, Chad]     Leon       ++  50   31
3  [Brad, Chad]     Leon       --  22   11

关键说明

  • 新增了对change字段的处理:因为它是数组,所以遍历里面的每个子字典,自动补充names和org_name这两个公共字段,不用手动逐行添加
  • 函数支持传入字典列表,遍历每个字典重复提取逻辑,适配不同长度的输入
  • 最后把res列转成合适的类型,避免出现浮点数(比如原代码里的4.0)
  • 所有字段都是动态检查的,字典里没有的字段会自动跳过,不用修改代码适配不同结构的字典

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:15:44