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

遍历嵌套字典创建Pandas DataFrame:如何修改for循环得到预期4个数据表

Python嵌套字典迭代生成Pandas表格修改方案

问题描述

需要输出对应的数据表,通过迭代Outcomes字典,将option 1、option 2下的所有列表值,以及row 1、row 2等行的取值全部整理进表格中。

现有代码

import pandas as pd

def Pandas(infos, title):
  display(pd.DataFrame(infos).style.set_caption(title).set_table_styles([{
    'selector': 'caption',
    'props': [
        ('color', 'red'),
        ('font-size', '16px'),
        ('text-align', 'center')
        ]
    }]))  


for id, info in Outcomes.items():
    for k in info:
        infos = {{f'{x}:': info[k][x]} if isinstance(info[k][x],list) else info[k][x] for x in info[k]}
        Pandas(infos, k)  

所用字典结构

Outcomes = {
    'Values':{
        'First': {
            'option 1': [12,345,5412],
            'option 2': [2315,32,1],
            'Additional Option': {'row 1': [232,3,1,3],
                         'row 2': [3,4,5,11],
                         'row 3': [15,6,12,34]}
        },
        'Second': {
            'option 1': [1,4,5,6,2],
            'option 2': [5,6,3,2,1],
            'Additional Option': {'row 1': [-5,3,1,2],
                         'row 2': [4,4,12,11],
                         'row 3': [67,6,5,34]}
        }
    },
    'Values 2':{
        'First': {
            'option 1': [12,345345,512412],
            'option 2': [2315,4,3],
            'Mega':{'row 1': [-45,12,33,1.3],
                    'row 2': [3.5,4.8,5,11]}
        }
    }
}

修改后的代码

核心修改逻辑为:先打平嵌套字典结构,把Additional Option、Mega等嵌套层级下的row行数据直接提到表格列维度,无需保留外层嵌套键。

import pandas as pd

def Pandas(infos, title):
  display(pd.DataFrame(infos).style.set_caption(title).set_table_styles([{
    'selector': 'caption',
    'props': [
        ('color', 'red'),
        ('font-size', '16px'),
        ('text-align', 'center')
        ]
    }]))  

# 修改后的迭代逻辑
for top_key, group in Outcomes.items():
    for table_name, content in group.items():
        table_data = {}
        for k, v in content.items():
            if isinstance(v, list):
                # 直接添加option类的列表数据
                table_data[k] = v
            elif isinstance(v, dict):
                # 展开嵌套的row类数据
                for row_k, row_v in v.items():
                    table_data[row_k] = row_v
        # 生成对应标题的表格
        Pandas(table_data, f"{top_key} - {table_name}")

运行以上代码即可生成所有符合要求的数据表,所有option和row的取值都会作为表格列展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:36:00