Pprint with custom float formats
I have a nested dictionary structure with tuple keys. Here's what the entry looks like when I am fairly printing a dictionary using pprint:
...
('A', 'B'): {'C': 0.14285714285714285,
'D': 0.14285714285714285,
'E': 0.14285714285714285,
'F': 0.14285714285714285,
'G': 0.14285714285714285,
'H': 0.14285714285714285,
'I': 0.14285714285714285},
...
It's pretty nifty, but I'd like to tweak it further by cutting some extra numbers from the floats. I thought it could be achieved by subclassing pprint.PrettyPrint
, but I don't know how it would be done.
Thank.
source to share
As you said, you can achieve this by subclassing PrettyPrinter
and rewriting the method format
. Note that the output is not only a formatted string, but also some flags.
After that, you can also generalize this and pass a dictionary with the desired formats for different types to the constructor:
class FormatPrinter(pprint.PrettyPrinter):
def __init__(self, formats):
super(FormatPrinter, self).__init__()
self.formats = formats
def format(self, obj, ctx, maxlvl, lvl):
if type(obj) in self.formats:
return self.formats[type(obj)] % obj, 1, 0
return pprint.PrettyPrinter.format(self, obj, ctx, maxlvl, lvl)
Example:
>>> d = {('A', 'B'): {'C': 0.14285714285714285,
... 'D': 0.14285714285714285,
... 'E': 0.14285714285714285},
... 'C': 255}
...
>>> FormatPrinter({float: "%.2f", int: "%06X"}).pprint(d)
{'C': 0000FF,
('A', 'B'): {'C': 0.14,
'D': 0.14,
'E': 0.14}}
source to share