我想知道是否有一种简单的方法来格式化字典输出的字符串,例如:
{
'planet' : {
'name' : 'Earth',
'has' : {
'plants' : 'yes',
'animals' : 'yes',
'cryptonite' : 'no'
}
}
}
...,一个简单的 str(dict) 只会给你一个非常难以理解的...
{'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}
就我对 Python 的了解而言,我将不得不编写大量带有许多特殊情况和 string.replace() 调用的代码,而这个问题本身看起来并不像 1000 行问题。
请建议根据此形状格式化任何 dict 的最简单方法。
最佳答案
根据您对输出的处理方式,一种选择是使用 JSON 进行显示。
import json
x = {'planet' : {'has': {'plants': 'yes', 'animals': 'yes', 'cryptonite': 'no'}, 'name': 'Earth'}}
print json.dumps(x, indent=2)
输出:
{
"planet": {
"has": {
"plants": "yes",
"animals": "yes",
"cryptonite": "no"
},
"name": "Earth"
}
}
这种方法需要注意的是,有些东西不能被 JSON 序列化。如果 dict 包含类或函数等不可序列化的项目,则需要一些额外的代码。
关于python - 如何很好地格式化dict字符串输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3733554/