如何在Python中格式化含可变数量子项的字典
Python字典格式化输出解决方案
不需要手动给字典添加换行符,直接用以下两种方法就能实现你要的缩进格式化效果:
方法一:使用json.dumps()
通过JSON模块的dumps()方法,指定缩进参数即可生成格式化字符串:
import json # 你的原始字典数据 my_dict = { "name": "BOB", "item1": { "item name": "bread", "quantity of item ": 10, "price of item": "3.00" }, "item2": { "item name": "milk", "quantity of item ": 15, "price of item": "9.00" } } # 生成带4空格缩进的格式化字符串 formatted_result = json.dumps(my_dict, indent=4, ensure_ascii=False) print(formatted_result)
执行后输出:
{ "name": "BOB", "item1": { "item name": "bread", "quantity of item ": 10, "price of item": "3.00" }, "item2": { "item name": "milk", "quantity of item ": 15, "price of item": "9.00" } }
方法二:使用pprint模块
Python内置的pprint(pretty print)模块专门用于美化打印数据结构:
from pprint import pprint # 直接打印格式化后的字典 pprint(my_dict, indent=4)
此方法无需转换为字符串,直接输出排版好的结果,效果和上面一致。
关键点说明:手动给字典添加\n字符是无效的,因为字典是数据存储结构,本身不存储格式信息,必须通过格式化方法将其转换为带缩进的字符串输出。
内容的提问来源于stack exchange,提问作者Aryan Vallabhbhai
相关产品推荐
相关产品推荐

