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

如何在Python中格式化打印嵌套JSON(字典)为指定格式

实现字典数据的格式化打印方法

你不需要移除特殊字符,核心是层级遍历字典+控制缩进量就能实现你要的格式。以下是针对你提供的数据的具体实现方案:

代码实现

dict_list = {
    "CIS3760": {
        "sections": [
            {
                "number": "0101",
                "professor": "greg",
                "times": [
                    {"days": "MWF", "time": "9:00", "type": "class"},
                    {"days": "MWF", "time": "9:00", "type": "class"}
                ]
            },
            {
                "number": "0202",
                "professor": "RUBY",
                "times": [
                    {"days": "tth", "time": "10:00", "type": "lab"},
                    {"days": "tth", "time": "9:00", "type": "class"}
                ]
            }
        ]
    }
}

def print_formatted(data, indent=0):
    # 处理最外层课程代码
    for course_code, course_info in data.items():
        print(f"{' ' * indent}{course_code}s\n")
        indent += 2
        print(f"{' ' * indent}Sections are")
        indent += 2
        
        # 遍历每个section
        for section in course_info["sections"]:
            for key, value in section.items():
                if key != "times":
                    print(f"{' ' * indent}{key}: {value}")
                else:
                    print(f"{' ' * indent}{key}\n")
                    indent += 4
                    
                    # 遍历每个时间项
                    for time_item in value:
                        for k, v in time_item.items():
                            # 匹配示例格式:days后无空格,其他字段加空格
                            print(f"{' ' * indent}{k}:{v}" if k == "days" else f"{' ' * indent}{k}: {v}")
                        print()  # 时间项之间空行
                    
                    indent -= 4
            print()  # section之间空行
        indent -= 4

print_formatted(dict_list)

输出效果

运行代码后会生成和你要求一致的格式:

CIS3760s

   Sections are
       number: 0101
       professor: greg
       times

           days:MWF
           time: 9:00
           type: class

           days:MWF
           time: 9:00
           type: class

       number: 0202
       professor: RUBY
       times

           days:tth
           time: 10:00
           type: lab

           days:tth
           time: 9:00
           type: class

核心逻辑说明

  1. 缩进控制:用indent变量管理每一层的空格数,不同层级内容对应不同缩进量,保证格式层级清晰。
  2. 类型区分处理:针对字典、列表分别遍历,逐个解析键值对和列表元素。
  3. 细节匹配:按照示例要求,单独处理days字段的输出格式,确保和目标格式完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 11:26:53