Python:为每个嵌套换行的字典打印漂亮的输出

10

我有以下数据结构:

{'row_errors': {'hello.com': {'template': [u'This field is required.']}}}

当我在Python中使用pprint时,我得到的结果是

{'row_errors': {'hello.com': {'template': [u'This field is required.']}}}

然而,我非常希望它能够像这样打印出来:

{'row_errors': 
    {'hello.com': 
        {'template': [u'This field is required.']}}}

这个能通过pprint进行配置吗?
我更喜欢使用pprint,因为我要在Jinja模板中打印它。


3
我向您提出另一种选择:import json; print(json.dumps(d, indent=4)) - wim
2
pprint() 并不十分可配置。 - Martijn Pieters
尝试将宽度参数更改为40:pprint(..., width=40)。然而,结果并不完全符合您所需的。 - GIZ
如果您只是想可视化嵌套结构(而不希望使用括号产生额外的行),可以考虑 https://pypi.org/project/asciitree/。一旦您正确获得了 OrderedDict 结构,它会提供漂亮的视觉效果。(非关联,只是一个粉丝) - combinatorist
1个回答

4

就像评论中wim所建议的那样,您可以使用json.dumps()

引用 Blender的回答:

json 模块已经使用indent参数实现了一些基本的漂亮打印功能:

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print json.dumps(parsed, indent=4, sort_keys=True)
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]

这将为每个JSON打开/关闭括号添加一行,因此格式比OP要长得多。(请考虑我的asciitree评论直接在OP上。) - combinatorist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接