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

Python如何从元组列表生成按表名分组的嵌套字典

从元组列表生成指定结构嵌套字典的解决方案

一、Pandas版本实现

你原有代码的问题是调用了set_index + orient='index',会生成键为列名的嵌套字典,修改为直接导出records格式即可:

import pandas as pd
import json

my_list = [
 ('actor', 'actor_id', 'integer', 'NO'),
 ('actor', 'first_name', 'character varying', 'NO'),
 ('actor_info', 'actor_id', 'integer', 'YES'),
 ('actor_info', 'first_name', 'character varying', 'YES')]
col = ['table', 'col_name', 'dtype', 'isnull']
df = pd.DataFrame(my_list, columns=col)

ff = df.groupby('table')[['col_name','dtype','isnull']].apply(
    lambda x: x.rename(columns={'col_name': 'column'}).to_dict(orient='records')
).to_dict()

print(json.dumps(ff, indent=1))

输出完全匹配你需要的结构。

二、原生Python实现(无需Pandas)

方法1:使用collections.defaultdict(简洁版)

from collections import defaultdict
import json

my_list = [
 ('actor', 'actor_id', 'integer', 'NO'),
 ('actor', 'first_name', 'character varying', 'NO'),
 ('actor_info', 'actor_id', 'integer', 'YES'),
 ('actor_info', 'first_name', 'character varying', 'YES')]

result = defaultdict(list)
for table, col_name, dtype, isnull in my_list:
    result[table].append({
        'column': col_name,
        'dtype': dtype,
        'isnull': isnull
    })

# 可选转为普通字典
result = dict(result)
print(json.dumps(result, indent=1))

方法2:普通字典实现(无需额外导入)

import json

my_list = [
 ('actor', 'actor_id', 'integer', 'NO'),
 ('actor', 'first_name', 'character varying', 'NO'),
 ('actor_info', 'actor_id', 'integer', 'YES'),
 ('actor_info', 'first_name', 'character varying', 'YES')]

result = {}
for table, col_name, dtype, isnull in my_list:
    if table not in result:
        result[table] = []
    result[table].append({
        'column': col_name,
        'dtype': dtype,
        'isnull': isnull
    })

print(json.dumps(result, indent=1))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 10:06:03