Python

How to Use Pretty Print Module in Python

This article will cover a guide on using the “Pretty Print” module and its available methods in Python. Also called pprint, this module is available in the standard Python library. All code samples in this article are tested with Python 3.9.5 on Ubuntu 21.04.

About Pprint

Pprint module can be used to improve look and feel and formatting of standard output printed using Python in a terminal. By formatting the output, you can improve its readability and even export it to an external file to store the better structured output. The usage of the pprint module can be best understood through examples, some of them are listed below.

Basic Syntax of the Pprint Method

Have a look at the code sample below:

from pprint import pprint

d = {"a": 1, "b": 2, "c": 3, "d": 4}
print(d)
pprint(d)

The example above illustrates the use of both print and pprint methods. The first line imports the pprint method from the pprint module. The “d” variable is a dictionary type object with key-value pairs. Next, the pprint method is called and the object to be printed is supplied to it as an argument (Python dictionary in this case).

After running the above code sample, you should get the following output:

{'a': 1, 'b': 2, 'c': 3, 'd': 4}
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

Both print and pprint methods produce the same output as no formatting has been applied to the output yet. The upcoming examples will show application of formatting to the output.

Converting a Single Line Output to Multiline Output Using Pprint

To convert a single line output to multiline output, you will have to supply the “width” variable as an argument to the pprint method. Have a look at the code sample below:

from pprint import pprint

d = {"a": 1, "b": 2, "c": 3, "d": 4}
pprint(d, width=1)

The code sample is the same as the example shown above, with a new argument called “width” having a value of 1. The width value can be used to specify the maximum number of characters allowed on one line. By default this value is 80. If nested objects / elements of an object overshoot the width constraints, they are moved to a new line. Since there is a constraint of just 1 character, each element will be moved to a new line using the best approach identified by Python for the object to be printed. This approach ensures that each element has a full line so that it is readable and not broken or truncated into partial words.

After running the above code sample, you should get the following output:

 {'a': 1,
 'b': 2,
 'c': 3,
 'd': 4}

Adding Indentation to Multiline Output Using Pprint

If you have a multiline string or you have broken a single line output to multiline output using the method explained above, you can use the “indent” argument to add spacing before each object in the output. Have a look at the code sample below:

from pprint import pprint

d = {"a": 1, "b": 2, "c": 3, "d": 4}
pprint(d, width=1, indent=4)

The code sample is the same as the example explained above. However, a new argument called “indent” with a value of 4 has been added. This will add indentation equal to 4 spaces before each object.

After running the above code sample, you should get the following output:

{   'a': 1,
    'b': 2,
    'c': 3,
    'd': 4}

Note that the “indent” argument will have no effect on single line outputs.

Limiting the Printed Output to Certain Levels

If the object you are printing contains nested objects, you can use the “depth” argument to limit the output to certain levels. Have a look at the code sample below:

from pprint import pprint

d = {"a": 1, "b": 2, "c": 3, "d": [4, 5]}
pprint(d, depth=1)

In the example above, the data is printed upto a depth level of 1. In other words, only objects that don’t contain any other nested objects are printed. The list “[4, 5]” has a depth level of 2 and will not be not printed. To indicate that it is hidden, three dots or ellipses are used.

After running the above code sample, you should get the following output:

{'a': 1, 'b': 2, 'c': 3, 'd': [...]}

Here is another example where a depth of 2 levels is used. The first nested element appears in the output but the second one doesn’t.

from pprint import pprint

d = {"a": 1, "b": 2, "c": 3, "d": [4, [5, 6]]}
pprint(d, depth=2)

After running the above code sample, you should get the following output:

{'a': 1, 'b': 2, 'c': 3, 'd': [4, [...]]}

Getting Pretty Printed Output as a Return Value

If you want to use the pretty printed output in other Python functions or assign it to a variable, you can use the “pformat” method. It is identical to the pprint method, except it doesn’t print anything but returns a formatted string. Have a look at the code sample below:

from pprint import pformat

d = {"a": 1, "b": 2, "c": 3, "d": [4, [5, 6]]}
pretty = pformat(d, depth=2)
print (pretty)

Instead of pprint, now pformat has been imported from the pprint module. The “pretty” variable stores the formatted string so that it can be used later in the code. The last statement prints the output of the pretty variable.

After running the above code sample, you should get the following output:

{'a': 1, 'b': 2, 'c': 3, 'd': [4, [...]]}

Using Json Module to Pretty Print a Python Dictionary

If you want to print a Python dictionary into a well indented JSON like structure, the pprint module might not be sufficient. In such a case, the “dumps” method from the json module produces a much better result. Have a look at the code sample below:

from pprint import pprint
from json import dumps

d = {"a": 1, "b": 2, "c": 3, "d": 4}
pprint (d, width=1, indent=4)
print (dumps(d, indent=4))

In addition to the pprint method, the “dumps” method from the json module has now been imported into the code sample. An argument called “indent” with a value of 4 has been supplied to the dumps method.

After running the above code sample, you should get the following output:

{   'a': 1,
    'b': 2,
    'c': 3,
    'd': 4}
{
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4
}

As you can see in the output, the dumps method produces a better formatted Python dictionary.

Conclusion

The pretty print or pprint module can be used to produce well formatted output in Python. The standard output of a lot of Python objects may not be exactly readable, especially when the data is large and has a lot of nested objects. In such cases, you can use pprint to improve readability and formatting of the output.

About the author

Nitesh Kumar

I am a freelancer software developer and content writer who loves Linux, open source software and the free software community.