Any way to properly pretty-print ordered dictionaries?

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

    The pprint() method is just invoking the __repr__() method of things in it, and OrderedDict doesn't appear to do much in it's method (or doesn't have one or something).

    Here's a cheap solution that should work IF YOU DON'T CARE ABOUT THE ORDER BEING VISIBLE IN THE PPRINT OUTPUT, which may be a big if:

    class PrintableOrderedDict(OrderedDict):
        def __repr__(self):
            return dict.__repr__(self)
    

    I'm actually surprised that the order isn't preserved... ah well.

    0 讨论(0)
  • 2020-12-07 15:09

    As of Python 3.8 : pprint.PrettyPrinter exposes the sort_dicts keyword parameter.

    True by default, setting it to False will leave the dictionary unsorted.

    >>> from pprint import PrettyPrinter
    
    >>> x = {'John': 1,
    >>>      'Mary': 2,
    >>>      'Paul': 3,
    >>>      'Lisa': 4,
    >>>      }
    
    >>> PrettyPrinter(sort_dicts=False).pprint(x)
    

    Will output :

    {'John': 1, 
     'Mary': 2, 
     'Paul': 3,
     'Lisa': 4}
    

    Reference : https://docs.python.org/3/library/pprint.html

    0 讨论(0)
  • 2020-12-07 15:11

    The following will work if the order of your OrderedDict is an alpha sort, since pprint will sort a dict before print.

    pprint(dict(o.items()))
    
    0 讨论(0)
提交回复
热议问题