Any way to properly pretty-print ordered dictionaries?

后端 未结 15 1493
春和景丽
春和景丽 2020-12-07 14:34

I like the pprint module in Python. I use it a lot for testing and debugging. I frequently use the width option to make sure the output fits nicely within my terminal window

15条回答
  •  既然无缘
    2020-12-07 14:51

    To print an ordered dict, e.g.

    from collections import OrderedDict
    
    d=OrderedDict([
        ('a', OrderedDict([
            ('a1',1),
            ('a2','sss')
        ])),
        ('b', OrderedDict([
            ('b1', OrderedDict([
                ('bb1',1),
                ('bb2',4.5)])),
            ('b2',4.5)
        ])),
    ])
    

    I do

    def dict_or_OrdDict_to_formatted_str(OD, mode='dict', s="", indent=' '*4, level=0):
        def is_number(s):
            try:
                float(s)
                return True
            except ValueError:
                return False
        def fstr(s):
            return s if is_number(s) else '"%s"'%s
        if mode != 'dict':
            kv_tpl = '("%s", %s)'
            ST = 'OrderedDict([\n'; END = '])'
        else:
            kv_tpl = '"%s": %s'
            ST = '{\n'; END = '}'
        for i,k in enumerate(OD.keys()):
            if type(OD[k]) in [dict, OrderedDict]:
                level += 1
                s += (level-1)*indent+kv_tpl%(k,ST+dict_or_OrdDict_to_formatted_str(OD[k], mode=mode, indent=indent, level=level)+(level-1)*indent+END)
                level -= 1
            else:
                s += level*indent+kv_tpl%(k,fstr(OD[k]))
            if i!=len(OD)-1:
                s += ","
            s += "\n"
        return s
    
    print dict_or_OrdDict_to_formatted_str(d)
    

    Which yields

    "a": {
        "a1": 1,
        "a2": "sss"
    },
    "b": {
        "b1": {
            "bb1": 1,
            "bb2": 4.5
        },
        "b2": 4.5
    }
    

    or

    print dict_or_OrdDict_to_formatted_str(d, mode='OD')
    

    which yields

    ("a", OrderedDict([
        ("a1", 1),
        ("a2", "sss")
    ])),
    ("b", OrderedDict([
        ("b1", OrderedDict([
            ("bb1", 1),
            ("bb2", 4.5)
        ])),
        ("b2", 4.5)
    ]))
    

提交回复
热议问题