Python Friday #93: Pretty Print for Python

If you try out a Python package in the REPL, the output of print() may not be the most useful one. In Ruby I used for this case the class PrettyPrint and as it turns out, Python has a similar built-in feature. Let’s have a look.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

The problem with print()

The print() method works great for a single line of text that you want to write to the console. When you try to write a list or a dictionary, print() will write them in one single line. This list of dictionaries with nested dictionaries is a good example:

If we use print() for the output it looks like this:

 

PrettyPrinter for Python

Python comes with a PrettyPrinter out of the box. All you need to do is to import pprint and instantiate the PrettyPrinter class:

The object from above looks a lot better when we print it with the PrettyPrinter:

 

Options for PrettyPrinter

PrettyPrinter has a few options to influence the output. If we indent the objects and reduce the width for our output, PrettyPrinter may even better show the nested values:

 

Conclusion

This little class is a great help when you need to inspect a dictionary in the console. We don’t need to install any packages and can use it in any Python version released after 1997.

2 thoughts on “Python Friday #93: Pretty Print for Python”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.