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:


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)


[ { '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}


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


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)


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


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


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


Returns True if the object passed has recursive structure.


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


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