Any way to properly pretty-print ordered dictionaries?

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

    Here’s a way that hacks the implementation of pprint. pprint sorts the keys before printing, so to preserve order, we just have to make the keys sort in the way we want.

    Note that this impacts the items() function. So you might want to preserve and restore the overridden functions after doing the pprint.

    from collections import OrderedDict
    import pprint
    
    class ItemKey(object):
      def __init__(self, name, position):
        self.name = name
        self.position = position
      def __cmp__(self, b):
        assert isinstance(b, ItemKey)
        return cmp(self.position, b.position)
      def __repr__(self):
        return repr(self.name)
    
    OrderedDict.items = lambda self: [
        (ItemKey(name, i), value)
        for i, (name, value) in enumerate(self.iteritems())]
    OrderedDict.__repr__ = dict.__repr__
    
    a = OrderedDict()
    a[4] = '4'
    a[1] = '1'
    a[2] = '2'
    print pprint.pformat(a) # {4: '4', 1: '1', 2: '2'}
    

提交回复
热议问题