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

如何将列表类型的字典写入txt文件并按指定格式输出?

解决方案

你原代码的问题在于循环字典时,每次都写入了整个字典的JSON字符串,而非逐个处理键和对应的列表。要实现你想要的格式,可以直接遍历字典的键值对,按行拼接内容:

基础实现代码

product_menu_list = {"Shirt": ["Red", "Orange", "Purple"], "Dress": ["Blue", "Yellow", "Green"]}

with open('product_record.txt', 'w') as f:
    for item, colors in product_menu_list.items():
        # 写入商品名称行
        f.write(f"{item}:\n")
        # 写入每个带缩进的颜色
        for color in colors:
            f.write(f"    {color}\n")
        # 写入空行分隔不同商品
        f.write("\n")

这段代码会生成你预期的格式,唯一的小问题是最后一个商品后会多一行空行。如果要完全匹配示例(最后无空行),可以调整为:

优化版代码(无末尾空行)

product_menu_list = {"Shirt": ["Red", "Orange", "Purple"], "Dress": ["Blue", "Yellow", "Green"]}

with open('product_record.txt', 'w') as f:
    # 把键值对转为列表方便判断是否为最后一项
    item_list = list(product_menu_list.items())
    for index, (item, colors) in enumerate(item_list):
        f.write(f"{item}:\n")
        for color in colors:
            f.write(f"    {color}\n")
        # 仅在非最后一项后添加空行
        if index != len(item_list) - 1:
            f.write("\n")

关键说明

  • 用product_menu_list.items()遍历字典,同时获取商品名(键)和对应的颜色列表(值)
  • 每个颜色前添加4个空格实现缩进,和你预期的格式一致
  • 优化版通过enumerate判断索引,避免最后多输出一行空行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 04:30:57