1 min read

Python Pprint Module

The pprint module provides a capability to "pretty-print" arbitrary Python data structures in a form which can be used as input to the interpreter. It is especially useful for printing complex data structures like nested dictionaries or lists in a readable format.

Importing the Module

import pprint

Basic Usage

pprint.pprint()

Prints the formatted representation of an object on sys.stdout.

import pprint

data = {
    'name': 'John Doe',
    'age': 30,
    'address': {
        'street': '123 Main St',
        'city': 'New York',
        'zip': '10001'
    },
    'hobbies': ['reading', 'cycling', 'hiking']
}

pprint.pprint(data)

pprint.pformat()

Returns the formatted representation of an object as a string.

import pprint

formatted_string = pprint.pformat(data)
print(f"Formatted data:\n{formatted_string}")

Customizing Output

You can customize the output using various parameters.

  • indent: Amount of indentation for each level.
  • width: Desired maximum number of characters per line.
  • depth: The number of levels to print.
  • compact: If true, tries to fit as many items as possible on each line.
import pprint

stuff = ['a' * 10, 'b' * 10, 'c' * 10, 'd' * 10]

pp = pprint.PrettyPrinter(indent=4, width=40, compact=True)
pp.pprint(stuff)

Handling Recursion

The pprint module handles recursive data structures correctly.

import pprint

a = [1, 2, 3]
a.append(a)

pprint.pprint(a)
# Output: [1, 2, 3, <Recursion on list with id=...>]

programming/python/python