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

如何在Python中将嵌套字典转换为指定格式的DataFrame

实现代码

直接用以下代码就能完成需求:

import pandas as pd

# 给定的嵌套字典
data = {
    "body-1": {
        "funtion-definition": ".c file",
        "funtion-definition-2": ".c file-2"
    },
    "body-2": {
        "funtion-definition": ".c file",
        "funtion-definition-2": ".c file-2"
    }
}

# 把嵌套字典拆解成扁平行数据
rows = []
for group, func_info in data.items():
    for func_name, file_name in func_info.items():
        rows.append({
            "Group": group,
            "function definition": func_name,
            ".c file": file_name
        })

# 创建DataFrame
df = pd.DataFrame(rows)

# 把同一分组的后续行Group列设为空字符串
df['Group'] = df['Group'].where(df['Group'] != df['Group'].shift(), '')

# 输出格式匹配的表格
print(df.to_string(index=False))

运行后输出结果:

Group     function definition     .c file
body-1    funtion-definition     .c file
          funtion-definition-2   .c file-2
body-2    funtion-definition     .c file
          funtion-definition-2   .c file-2

核心逻辑说明

  1. 先把嵌套字典逐层拆解成DataFrame需要的单行数据格式;
  2. 用shift()对比当前行与上一行的Group值,重复值替换为空,实现分层显示效果;
  3. 用to_string(index=False)隐藏默认索引,让输出完全匹配需求样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 23:57:43