如何在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
核心逻辑说明
- 缩进控制:用
indent变量管理每一层的空格数,不同层级内容对应不同缩进量,保证格式层级清晰。 - 类型区分处理:针对字典、列表分别遍历,逐个解析键值对和列表元素。
- 细节匹配:按照示例要求,单独处理
days字段的输出格式,确保和目标格式完全一致。
内容的提问来源于stack exchange,提问作者Bahaa Zuraik
相关产品推荐
相关产品推荐

