Any way to properly pretty-print ordered dictionaries?

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

    I've tested this unholy monkey-patch based hack on python3.5 and it works:

    pprint.PrettyPrinter._dispatch[pprint._collections.OrderedDict.__repr__] = pprint.PrettyPrinter._pprint_dict
    
    
    def unsorted_pprint(data):
        def fake_sort(*args, **kwargs):
            return args[0]
        orig_sorted = __builtins__.sorted
        try:
            __builtins__.sorted = fake_sort
            pprint.pprint(data)
        finally:
            __builtins__.sorted = orig_sorted
    

    You make pprint use the usual dict based summary and also disable sorting for the duration of the call so that no keys are actually sorted for printing.

提交回复
热议问题