You'd need to create your own subclass of the pprint.PrettyPrinter
class, and override the .format()
method:
from pprint import PrettyPrinter, _recursion
class MyPrettyPrinter(PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, OrderedDict):
if not object:
return "()", True, False
objid = id(object)
if maxlevels and level >= maxlevels:
return "(...)", False, objid in context
if objid in context:
return _recursion(object), False, True
context[objid] = 1
readable = True
recursive = False
components = []
append = components.append
level += 1
selfformat = self.format
for k, v in sorted(object.items()):
krepr, kreadable, krecur = selfformat(k, context, maxlevels, level)
vrepr, vreadable, vrecur = selfformat(v, context, maxlevels, level)
append('({}, {})'.format(krepr, vrepr))
readable = readable and kreadable and vreadable
if krecur or vrecur:
recursive = True
del context[objid]
return '({})'.format(', '.join(components)), readable, recursive
formatted, readable, recursion = PrettyPrinter.format(self, object, context, maxlevels, level)
if isinstance(object, unicode):
formatted = formatted.lstrip('u')
return formatted, readable, recursion
We let the base class do most of the work and only format the OrderedDict
explicitly; it has a custom __repr__
which means that the original pprint
implementation just uses that instead of recursing over it.
Then use this class instead of direct calls to pprint.pprint()
:
mypprint = MyPrettyPrinter()
mypprint.pprint(x)
This produces:
>>> mypprint = MyPrettyPrinter()
>>> mypprint.pprint(x)
[(('D-ID', 'clci-2'), ('R', '1691')),
(('D-ID', 'dallas-pcc-1'), ('R', '5498')),
(('D-ID', 'gx-1'), ('R', '2275')),
(('D-ID', 'gx-2'), ('R', '0')),
(('D-ID', 'ocs-1'), ('R', '31735')),
(('D-ID', 'ocs-2'), ('R', '0')),
(('D-ID', 'pcc-gx-1'), ('R', '46351')),
(('D-ID', 'rgx-1'), ('R', '907')),
(('D-ID', 'rgx-2'), ('R', '1010')),
(('D-ID', 'rocs-1'), ('R', '915')),
(('D-ID', 'rocs-2'), ('R', '1033'))]