pprint — data pretty printer

pprint is not JSON: sort_dicts, width, and depth for stable pretty-printed Python objects.

モジュールページの本文は現在英語です。

pprint pretty-prints Python objects as Python syntax, not as JSON. Import it as import pprint. It can print types that json.dumps cannot encode, and it does not produce a JSON document even when the object looks like a dict. The json page is the place for dumps, loads, and normalizing JSON before a text diff.

Stable output depends on explicit parameters. pprint.pprint sorts dict keys by default (sort_dicts=True). pprint.pp, added as a convenience wrapper, defaults to sort_dicts=False, which keeps insertion order. width controls wrapping. depth replaces deeper nesting with .... Recursion is detected, but the cycle marker includes a memory id, so this page does not use a recursive object as an expected-output example.

Examples were run against Python 3.13.12. Links point to the Python 3.13 documentation.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

sort_dicts, depth, and stable parameters

With depth=2, the nested {"z": 3} is shown as {...}. With depth left at None, the full nesting is printed. sort_dicts=False keeps {"b": 1, "a": 2} in insertion order; sort_dicts=True prints {"a": 2, "b": 1}. width=40 is fixed so wrapping does not depend on the terminal.

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.

ParameterDescription
objectAny Python object. This example uses dicts, not a JSON string.
widthThe preferred line width. The example uses 40 so the output does not depend on the terminal size.
depthThe number of nesting levels to show. None means no cap. Deeper values are replaced with ....
sort_dictsTrue 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.
python
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)

Official documentation →