Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pprint with custom float formats

Tags:

python

pprint

I have a nested dictionary structure with tuple keys. Here's what an entry looks like when I pretty-print the 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 customize it further by cutting down some extra digits from the floats. I was thinking that it'd be possible to achieve by subclassing pprint.PrettyPrint but I don't know how that would be done.

Thanks.

like image 832
Berk Özbalcı Avatar asked Jun 04 '17 17:06

Berk Özbalcı


People also ask

How do I format a float number in Python?

In Python, there are various methods for formatting data types. The %f formatter is specifically used for formatting float values (numbers with decimals). We can use the %f formatter to specify the number of decimal numbers to be returned when a floating point number is rounded up.

How do you print a float variable?

Use the print() function to print a float value, e.g. print(f'{my_float:. 2f}') . A formatted string literal can be used if you need to round the float to N decimal places.

What is Pprint Pformat?

pprint() − prints the formatted representation of PrettyPrinter object. pformat() − Returns the formatted representation of object, based on parameters to the constructor.

How do you Pprint in Python?

To use pprint, begin by importing the library at the top of your Python file. From here you can either use the . pprint() method or instantiate your own pprint object with PrettyPrinter() .


1 Answers

As you said, you can achieve this by subclassing PrettyPrinter and overwriting the format method. Note that the output is not only the formatted string, but also some flags.

Once you're at it, you could also generalize this and pass a dictionary with the desired formats for different types into 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}}
like image 93
tobias_k Avatar answered Oct 20 '22 15:10

tobias_k