· Python · 3 min read

Python Pretty Printing: Using the pprint Module Effectively

Python Pretty Printing: Using the pprint Module Effectively

Introduction to Pretty Printing and Its Utility

Python’s pretty-print library, known as pprint, provides a simple and effective way to present complex data structures, such as dictionaries or lists, in an organized and readable format. Making the output more visually appealing is especially helpful when working with structured data, as it enables easier tracking and debugging of errors in code.

Properties and Parameters of the pprint Module

The pprint module comes with several useful functions and parameters that can be customized to achieve different styles of pretty-printing.

Functions in the pprint Module

  1. pprint.pprint: This is the fundamental function for pretty-printing objects in Python. It accepts the following parameters:

    • object: The object to be pretty-printed.
    • indent: The number of spaces to indent for each level. Default is 1.
    • width: The maximum allowed number of characters for each line. Default is 80.
    • depth: The maximum depth level to pretty-print. Default is None.
    • sort_dicts: Sort dictionary keys alphabetically. Default is True.
    • stream: The stream to output the pretty-print result. Default is None, which uses sys.stdout.
  2. pprint.pformat: This function is similar to pprint, but instead of printing the formatted object, it returns a formatted string. It accepts the same parameters as pprint.

Special Parameter Types

  • Compact: A boolean parameter, default is False. When set to True, the pretty-print will try to fit more data on each line.

Simplified Real-Life Example

Suppose you have a dictionary containing information about books and their authors. You can use pprint to display the data in an organized manner.

from pprint import pprint

books = {
    "book1": {"title": "The Catcher in the Rye", "author": "J.D. Salinger"},
    "book2": {"title": "To Kill a Mockingbird", "author": "Harper Lee"},
    "book3": {"title": "1984", "author": "George Orwell"},
}

pprint(books)

This code produces the following output:

{'book1': {'author': 'J.D. Salinger', 'title': 'The Catcher in the Rye'},
 'book2': {'author': 'Harper Lee', 'title': 'To Kill a Mockingbird'},
 'book3': {'author': 'George Orwell', 'title': '1984'}}

Complex Real-Life Example

Consider a more complex example with nested dictionaries and lists.

crew_members = {
    "captain": {
        "name": "John Smith",
        "jobs": ["Navigation", "Leadership", "Tactics"],
        "years_of_experience": 15,
    },
    "first_mate": {
        "name": "Sarah Davis",
        "jobs": ["Mechanics", "First Aid", "Management"],
        "years_of_experience": 10,
    },
    "engineer": {
        "name": "Henry Adams",
        "jobs": ["Engineering", "Maintenance"],
        "years_of_experience": 5,
    },
}

pprint(crew_members, indent=2, width=40, compact=True)

The output will be as follows:

{ 'captain': { 'jobs': [ 'Navigation',
                         'Leadership',
                         'Tactics'],
               'name': 'John Smith',
               'years_of_experience': 15},
  'engineer': { 'jobs': [ 'Engineering',
                          'Maintenance'],
                'name': 'Henry Adams',
                'years_of_experience': 5},
  'first_mate': { 'jobs': [ 'Mechanics',
                            'First Aid',
                            'Management'],
                  'name': 'Sarah Davis',
                  'years_of_experience': 10}}

As seen above, the nested elements are aligned consistently, and the output is now more readable.

Personal Tips on Using the pprint Module

  1. Use pprint for debugging: When working with complex data structures, utilize pprint instead of the standard print function for enhanced readability when debugging your code.
  2. Adjust the width and compact settings: Tweak these parameters to obtain the desired output for better understanding of the structure and relationships within the data.
  3. Use pprint.pformat to create a formatted output: If you need to store the formatted output as a string, use pprint.pformat instead of pprint.
  4. Limit the depth: When dealing with very deep nested structures, use the depth parameter to limit the levels of nesting displayed. This prevents cluttered output and helps focus on the relevant sections.
  5. Control dictionary sorting: If you need to order dictionaries by keys or values, use the sort_dicts parameter to control whether to sort the keys or not.

By following these tips and experimenting with the different functions and settings in the pprint module, you can achieve clean and organized outputs in your projects, making your code development process more efficient and effective.

Share: