Python Basics: Inspecting Data with pprint
A long dictionary can be hard to scan in a terminal. Python’s pprint module formats nested data across lines, making it easier to inspect a script’s intermediate results.
Use Python 3.12 or newer on Linux. Each example runs independently and only prints sample data.
Print a readable summary
Save as demo_pprint_1.py:
from pprint import pp
report = {
"service": "worker",
"regions": ["east", "west"],
"healthy": True,
}
pp(report, width=32)Run it from the directory where you saved it:
python3 demo_pprint_1.pyOutput:
{'service': 'worker',
'regions': ['east', 'west'],
'healthy': True}pp() writes the result directly to standard output. Adjust width to fit your terminal; it is a target, so a single long value can exceed it. Formatting changes the display without changing the dictionary.
Keep formatted text for later
Save as demo_pprint_2.py:
from pprint import pformat
settings = {"zebra": 3, "apple": 1}
original_order = pformat(settings, sort_dicts=False)
sorted_keys = pformat(settings, sort_dicts=True)
print(original_order)
print(sorted_keys)Run it from the directory where you saved it:
python3 demo_pprint_2.pyOutput:
{'zebra': 3, 'apple': 1}
{'apple': 1, 'zebra': 3}pformat() returns a string you can include in a diagnostic message. pp() preserves dictionary insertion order by default; pformat() and pprint() sort keys by default. Set sort_dicts explicitly when the choice matters. Sorting the display does not reorder the source dictionary.
Limit nested detail
Save as demo_pprint_3.py:
from pprint import pp
report = {
"jobs": [{"name": "backup", "status": "done"}],
"count": 1,
}
pp(report, depth=1)
print("Jobs still present:", len(report["jobs"]))Run it from the directory where you saved it:
python3 demo_pprint_3.pyOutput:
{'jobs': [...], 'count': 1}
Jobs still present: 1depth replaces deeper containers with ... in the output. Increase it or omit it when you need the details. It does not limit the number of top-level items or remove data from memory.
Treat this output as a debugging view. For exchanging data with another program, choose an appropriate format such as JSON. Do not use eval() to load diagnostic text. Review or redact private values before printing or logging them: depth limits are not a secret filter.
References
Acknowledgements
This post was created with assistance from AI.