Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
267: The pprint Module for Readable Output
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
There are no comments for now.