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

Python如何将列表与元组列表转换为嵌套字典结构

问题原因

你的代码遍历逻辑维度错误,当前是按列(标题数量)遍历,每次仅给外层字典的key赋值单个键值对,还错误使用join将元组内的多个值拼接为单个字符串,无法得到嵌套结构。另外注意原title列表里的字段是字符串类型,需要加引号声明。

修正后代码

data = [('2015-10-08', '2016-07-17'), ('Alex', 'Jerry'), (5, 6)]
title = ['Date', 'Name', 'Age']
output = {}

# 转置data将列存储转为行存储,遍历每行数据
for idx, row in enumerate(zip(*data), start=1):
    # 行数据和表头打包生成内层字典,序号转字符串作为外层key
    output[str(idx)] = dict(zip(title, row))

print(output)

运行输出

{'1': {'Date': '2015-10-08', 'Name': 'Alex', 'Age': 5}, '2': {'Date': '2016-07-17', 'Name': 'Jerry', 'Age': 6}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:57:02