Skip to Content
Course content

267: The pprint Module for Readable Output

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this happen countless times: a developer is debugging a complex piece of code, they have a massive nested dictionary or a list of objects, and they throw a print() statement at it. Then, they spend the next ten minutes squinting at a single, monolithic wall of text that wraps haphazardly across their terminal, trying to figure out where one key ends and the next begins. They usually tell me, "I guess I'll just have to write a custom loop to iterate through the keys and print them one by one."

Thinking standard print is enough for nested data

Let's look at why that approach is a waste of your time. Imagine you're working with a response from a movie database API. You've got a structure that looks something like this:

movies = [
    {"title": "Inception", "year": 2010, "cast": ["Leonardo DiCaprio", "Joseph Gordon-Levitt"], "details": {"genre": "Sci-Fi", "rating": 8.8, "awards": {"Oscars": 4, "BAFTAs": 2}}},
    {"title": "The Matrix", "year": 1999, "cast": ["Keanu Reeves", "Laurence Fishburne"], "details": {"genre": "Sci-Fi", "rating": 8.7, "awards": {"Oscars": 4, "BAFTAs": 1}}},
    {"title": "Interstellar", "year": 2014, "cast": ["Matthew McConaughey", "Anne Hathaway"], "details": {"genre": "Sci-Fi", "rating": 8.6, "awards": {"Oscars": 1, "BAFTAs": 2}}}
]

print(movies)

When you run this, Python prints it as one giant string. Depending on your terminal width, it's a mess. If the data gets any larger, it becomes practically impossible to visually parse. Writing a loop to fix this is a "rabbit hole" task—you start by printing keys, then you realize you need to handle nested lists, then you realize you need to handle nested dictionaries, and suddenly you've spent an hour writing a formatting function instead of fixing your actual bug.

Using pprint to actually see your data structure

This is where the pprint (pretty-print) module comes in. It's part of the standard library, so you don't need to install anything. It does exactly what it sounds like: it analyzes the structure of your data and formats it with sensible indentation and line breaks.

Here is how I actually handle this in my daily workflow:

from pprint import pprint

movies = [
    {"title": "Inception", "year": 2010, "cast": ["Leonardo DiCaprio", "Joseph Gordon-Levitt"], "details": {"genre": "Sci-Fi", "rating": 8.8, "awards": {"Oscars": 4, "BAFTAs": 2}}},
    {"title": "The Matrix", "year": 1999, "cast": ["Keanu Reeves", "Laurence Fishburne"], "details": {"genre": "Sci-Fi", "rating": 8.7, "awards": {"Oscars": 4, "BAFTAs": 1}}},
    {"title": "Interstellar", "year": 2014, "cast": ["Matthew McConaughey", "Anne Hathaway"], "details": {"genre": "Sci-Fi", "rating": 8.6, "awards": {"Oscars": 1, "BAFTAs": 2}}}
]

pprint(movies)

The difference is night and day. pprint will automatically break the lists and dictionaries into multiple lines, aligning the braces and brackets so you can actually track the hierarchy. I personally find it indispensable when dealing with JSON-like data.

Now, pprint isn't just a "one-size-fits-all" function; it has a few knobs you can turn to make the output fit your screen better:

  • width: Tells Python when to wrap the line. If you have a very narrow terminal, you can set this lower.
  • indent: Controls how many spaces are used for each nesting level.
  • depth: This is a lifesaver for truly massive objects. If you set depth=2, Python will print the first two levels and then replace deeper structures with ellipses (...), preventing your terminal from being flooded with 10,000 lines of text.

For example, if you're dealing with a deeply nested configuration file, you might use it like this:

pprint(huge_config_dict, width=40, depth=3)

It's a simple tool, but using it consistently saves you from that specific kind of mental fatigue that comes from staring at unformatted strings.




📋 Practical Task

Formatting a Nested User Permissions Audit

You are auditing a system's user permissions. You have a dictionary containing multiple users, their assigned roles, and the specific permissions associated with those roles. Currently, the data is a mess and hard to read.

Your Task: Use the pprint module to print the user_audit dictionary so that it is vertically expanded and easy to read. Additionally, use the width parameter to limit the output to 50 characters per line to ensure it fits in a narrow log file.

from pprint import pprint

user_audit = {
    "admin_user": {
        "id": 1,
        "roles": ["superuser", "billing_admin"],
        "permissions": {"system": ["read", "write", "execute"], "billing": ["invoice_create", "invoice_delete", "refund_issue"]},
        "last_login": "2023-10-01 10:00:00"
    },
    "staff_user": {
        "id": 2,
        "roles": ["editor"],
        "permissions": {"system": ["read"], "content": ["edit_post", "publish_post", "delete_post"]},
        "last_login": "2023-10-02 14:30:00"
    },
    "guest_user": {
        "id": 3,
        "roles": ["viewer"],
        "permissions": {"system": ["read"], "content": ["view_post"]},
        "last_login": "2023-10-03 09:15:00"
    }
}

# Your code here:
# Use pprint to print user_audit with a width of 50
Rating
0 0

There are no comments for now.

to be the first to leave a comment.