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

如何从嵌套字典中提取值并生成指定格式输出?

提取嵌套字典数据生成指定格式文本

你可以通过两层遍历嵌套字典的方式,提取所需字段并拼接成目标格式的字符串,具体实现如下:

直接打印输出的代码

text = {
    1: {
        1: {"ch.name": "The Boy Who Lived", "pages": "146"},
        2: {"ch.name": "The Vanishing Glass", "pages": "126"},
    },
    2: {
        1: {"ch.name": "The Worst Birthday", "pages": "129"},
        2: {"ch.name": "Dobby's Warning", "pages": "125"},
    },
}

# 遍历每个季的编号和对应章节集合
for season_num, chapters in text.items():
    # 遍历当前季下的每个章节编号和章节信息
    for ch_num, ch_details in chapters.items():
        # 提取章节名和页数,拼接成指定格式
        output_line = f"Watched Season {season_num} Chapter {ch_num}:{ch_details['ch.name']},{ch_details['pages']}"
        print(output_line)

保存结果到列表的代码(方便后续处理)

如果需要把所有结果先存储起来再使用,可以将生成的字符串存入列表:

text = {
    1: {
        1: {"ch.name": "The Boy Who Lived", "pages": "146"},
        2: {"ch.name": "The Vanishing Glass", "pages": "126"},
    },
    2: {
        1: {"ch.name": "The Worst Birthday", "pages": "129"},
        2: {"ch.name": "Dobby's Warning", "pages": "125"},
    },
}

output_list = []
for season_num, chapters in text.items():
    for ch_num, ch_details in chapters.items():
        output_line = f"Watched Season {season_num} Chapter {ch_num}:{ch_details['ch.name']},{ch_details['pages']}"
        output_list.append(output_line)

# 按需使用列表中的内容,比如打印所有结果
for line in output_list:
    print(line)

代码说明

  • 外层循环负责遍历字典中的季编号和该季对应的章节字典
  • 内层循环遍历每个章节的编号和详细信息字典
  • 利用Python的f-string格式化语法,将提取到的字段按要求拼接成目标字符串
  • 两种写法分别适用于直接输出和需要后续批量处理的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 04:15:43