如何漂亮地打印嵌套词典? [英] 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)
我只是想为每个嵌套添加一个缩进("\t"
),这样我就得到了这样的东西:
I simply want an indentation ("\t"
) 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('\t' * indent + str(key))
if isinstance(value, dict):
pretty(value, indent+1)
else:
print('\t' * (indent+1) + str(value))
这篇关于如何漂亮地打印嵌套词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文