如何漂亮地打印嵌套字典? [英] How to pretty print nested dictionaries?
本文介绍了如何漂亮地打印嵌套字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 中漂亮地打印深度为 ~4 的字典?我尝试使用 pprint()
进行漂亮的打印,但没有奏效:
How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint()
, but it did not work:
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
我只想为每个嵌套使用缩进 (" "
),这样我就会得到这样的结果:
I simply want an indentation (" "
) for each nesting, so that I get something like this:
key1
value1
value2
key2
value1
value2
等等.
我该怎么做?
推荐答案
我不确定您希望格式的具体外观如何,但您可以从这样的函数开始:
I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:
def pretty(d, indent=0):
for key, value in d.items():
print(' ' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print(' ' * (indent+1) + str(value))
这篇关于如何漂亮地打印嵌套字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文