Any way to properly pretty-print ordered dictionaries?

后端 未结 15 1524
春和景丽
春和景丽 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 15:03

    Here is my approach to pretty print an OrderedDict

    from collections import OrderedDict
    import json
    d = OrderedDict()
    d['duck'] = 'alive'
    d['parrot'] = 'dead'
    d['penguin'] = 'exploded'
    d['Falcon'] = 'discharged'
    print(d)
    print(json.dumps(d,indent=4))
    
    OutPut:
    
    OrderedDict([('duck', 'alive'), ('parrot', 'dead'), ('penguin', 'exploded'), ('Falcon', 'discharged')])
    
    {
        "duck": "alive",
        "parrot": "dead",
        "penguin": "exploded",
        "Falcon": "discharged"
    }
    

    If you want to pretty print dictionary with keys in sorted order

    print(json.dumps(indent=4,sort_keys=True))
    {
        "Falcon": "discharged",
        "duck": "alive",
        "parrot": "dead",
        "penguin": "exploded"
    }
    

提交回复
热议问题