【问题标题】:Inconsistent printing of nested dict using pprint in Python在 Python 中使用 pprint 打印嵌套字典不一致
【发布时间】:2017-08-22 17:50:59
【问题描述】:

我用pprint 漂亮地打印了一个大的嵌套dict

import pprint
import json


with open('config.json', 'r') as fp:
    conf = fp.read()


pprint.pprint(json.loads(conf))



{u'cust1': {u'videotron': {u'temperature': u'3000K',
                           u'image_file': u'bloup.raw',
                           u'light_intensity': u'20',
                           u'size': [1920, 1080],
                           u'patches': [[94, 19, 247, 77],
                                        [227, 77, 293, 232],
                                        [77, 217, 230, 279],
                                        [30, 66, 93, 211]]}},
 u'cust2': {u'Rogers': {u'accuracy': True,
                        u'bleed': True,
                        u'patches': [[192,
                                      126,
                                      10,
                                      80],
                                     [318,
                                      126,
                                      10,
                                      80], ...

第二级列表cust2.Rogers.patches 是展开而cust1.videotron.patches 不是。我希望两个 not 都展开,即打印在同一行。有人知道怎么做吗?

【问题讨论】:

    标签: python json printing console pprint


    【解决方案1】:

    您可以使用两个参数:widthcompact(最后一个可能不适用于 Python 2)。

    width -- 限制水平空间。

    这里是compact的描述:

    如果 compact 为 false(默认值),则长序列的每个项目将被格式化为单独的行。如果 compact 为真,则在每个输出行上都会格式化适合宽度的尽可能多的项目。

    但据我了解,您无法告诉 pprint 任何有关数据结构以及您希望如何打印特定元素的信息。

    【讨论】:

    • 感谢 danil,我确实看到了 compact,但我在 py2 上工作。我没想到我的问题来自有限的width,就是这样,谢谢!
    【解决方案2】:

    PrettyPrinter 控件

    pprint 模块中的PrettyPrinter 接受各种参数来控制输出格式:

    • 缩进:为每个递归级别添加的缩进量
    • 宽度:使用宽度参数限制所需的输出宽度
    • depth:可以打印的层数
    • compact:当为 true 时,将在每个输出行上格式化适合宽度的尽可能多的项目

    JSON 替代

    json module 本身有自己的 pprint 替代方案,使用 json.dumpsindent 参数集:

    >>> print json.dumps(conf, indent=4)
    {
        "cust2": {
            "Rogers": {
                "patches": [
                    [
                        192, 
                        126, 
                        10, 
                        80
                    ], 
           ...
    

    具体问题

    第二级列表 cust2.Rogers.patches 是展开的,而 cust1.videotron.patches 不是。我不希望两者都展开,即打印在同一行。

    上述工具都不能让您按照指定的方式直接解决您的问题。为了得到你想要的,你需要编写一些自定义的漂亮打印代码。

    【讨论】:

      猜你喜欢
      • 2011-11-26
      • 1970-01-01
      • 2018-09-12
      • 2022-12-03
      • 1970-01-01
      • 2016-12-28
      • 2021-12-02
      • 2021-12-11
      相关资源
      最近更新 更多