How to use pprint in Python?

Pratik Choudhari

pprint is used to print a beautified representation of an object in Python. It is available as a standard library that comes preinstalled with Python.

This article will explore how pprint is used and what formatting options it provides.

1. pprint.pprint(object)

This is the most famous function from the pprint module.

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)

It passes the arguments and keyword arguments to the PrettyPrinter class constructor. Following are the arguments accepted by the function:

Example:

from pprint import pprint data = [{"language": "Python", "application": ["Data Science", "Automation", "Scraping", "API"]}, {"language": "Javascript", "application": ["Web Development", "API", "Web Apps", "Games"]}] pprint(data, indent=3)

Output:

[ { 'application': ['Data Science', 'Automation', 'Scraping', 'API'], 'language': 'Python'}, { 'application': ['Web Development', 'API', 'Web Apps', 'Games'], 'language': 'Javascript'}]

Example with and without sort_dicts:

from pprint import pprint values = {'a': 1, 'd': 4, 'b': 2} pprint(values) # {'a': 1, 'b': 2, 'd': 4} pprint(values, sort_dicts=False) # {'a': 1, 'd': 4, 'b': 2}

pprint.pformat(object)

pformat() is similar to pprint(), the distinctions are:

Example:

from pprint import pformat nested_dict = [{"language": "Python", "application": ["Data Science", "Automation", "Scraping", "API"]}, {"language": "Javascript", "application": ["Web Development", "API", "Web Apps", "Games"]}] string_representation = pformat(nested_dict) print(string_representation)

Output:

[{'application': ['Data Science', 'Automation', 'Scraping', 'API'], 'language': 'Python'}, {'application': ['Web Development', 'API', 'Web Apps', 'Games'], 'language': 'Javascript'}]

pprint.pp(object)

Alias to pprint.pprint(), available from Python 3.8 and above.

pprint.isreadable(object)

Returns True if the object passed is readable by pprint, if an object is readable it can be pretty printed.

pprint.isrecursive(object)

Returns True if the object passed has recursive structure.

Example:

from pprint import pprint, isrecursive recursive_dict = {} recursive_dict[0] = recursive_dict[1] = recursive_dict print(isrecursive(recursive_dict)) pprint(recursive_dict)

Output:

True {0: <Recursion on dict with id=140056761037664>, 1: <Recursion on dict with id=140056761037664>}

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link *

* This is an affiliate link. By clicking on it you will not have any additional costs, instead you will support me and my project. Thank you! 🙏

Check out my Courses