pprint.pprint
pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False)
pprint.pp(object, *args, sort_dicts=False, **kwargs)Pretty-print a nested dict with a depth cap, then show how sort_dicts changes key order.
| Parameter | Description |
|---|---|
object | Any Python object. This example uses dicts, not a JSON string. |
width | The preferred line width. The example uses 40 so the output does not depend on the terminal size. |
depth | The number of nesting levels to show. None means no cap. Deeper values are replaced with .... |
sort_dicts | True sorts dict keys for a stable order (the pprint default). False keeps insertion order (the pp default). |
Returns: None. The formatted text is written to stream, which defaults to stdout.
- underscore_numbers and compact are part of the official 3.13 signature and are left at their defaults here.
import pprint
data = {"b": 2, "a": {"y": 2, "x": {"z": 3}}}
pprint.pprint(data, width=40, depth=2, sort_dicts=True)
print("---")
pprint.pprint(data, width=40, sort_dicts=True)
print("---")
unordered = {"b": 1, "a": 2}
pprint.pprint(unordered, width=40, sort_dicts=False)
pprint.pprint(unordered, width=40, sort_dicts=True)Expected output
{'a': {'x': {...}, 'y': 2}, 'b': 2}
---
{'a': {'x': {'z': 3}, 'y': 2}, 'b': 2}
---
{'b': 1, 'a': 2}
{'a': 2, 'b': 1}Related: json (dumps and stable JSON)