Python

Python pprint — Format Nested Data with Width, Depth, and Compact

A nested list of dicts printed with print comes out as one long line that no one can scan. The pprint module formats the same data across lines, aligned and sorted, so a person can read the shape at a glance. This guide takes the controls in turn: width, key sorting, depth, compact packing, a reusable printer object, and the two traps that catch first-time users.

Written November 14, 2026 · Tested with Python 3.12.3 · 10 min read

By the end of this guide
  • The main program: pprint and pformat
  • Width: where the lines break
  • sortdicts: sorted keys or insertion order
  • Depth: cut off the deep levels

Written November 14, 2026

Tested with Python 3.12.3

What this guide is

The pprint module prints data structures in a form a person can read. Where print puts a whole nested value on one line, pprint breaks it across lines at the container boundaries, indents the inner levels to line up, and sorts dict keys so two runs of the same program produce the same layout. Two entry points share the work: pprint.pprint sends the formatted text to the screen, and pprint.pformat returns the same text as a string for code that writes it to a file, a log, or a message. The module formats the built-in containers: lists, tuples, dicts, and sets, plus the values nested inside them.

The main program: pprint and pformat

The difference shows on the first nested value. print keeps the insertion order of each dict and runs both records together on one line. pprint sorts each dict by key and gives each record its own line. The pformat call at the end returns that layout as a string, which the last line proves by counting its lines:

Python
import pprint
data = [{"name": "ada", "langs": ["python", "rust"], "active": True}, {"name": "bo", "langs": ["go"], "active": False}]
print(data)
pprint.pprint(data)
text = pprint.pformat(data)
print(type(text).__name__, len(text.splitlines()))

The exact output:

Output
[{'name': 'ada', 'langs': ['python', 'rust'], 'active': True}, {'name': 'bo', 'langs': ['go'], 'active': False}]
[{'active': True, 'langs': ['python', 'rust'], 'name': 'ada'},
 {'active': False, 'langs': ['go'], 'name': 'bo'}]
str 2

The sorted keys are the part readers rely on most. Two dicts with the same items in a different order format to the same text, so formatted output can be compared line by line, stored in a test, or read in a log without the order of construction getting in the way. pformat is the form to reach for when the text has a destination other than the screen: the string it returns is the exact text pprint would have printed, with no trailing newline added.

Width: where the lines break

The width argument sets the longest line the formatter tries to produce, and the default is 80. A value that fits the width stays on one line. A value that does not fit breaks at container boundaries, and a list whose items cannot share a line puts one item on each line:

Python
import pprint
words = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel"]
pprint.pprint(words)
pprint.pprint(words, width=30)
lines = pprint.pformat(words, width=30).splitlines()
print(len(lines), lines[0])

The exact output:

Output
['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf', 'hotel']
['alpha',
 'bravo',
 'charlie',
 'delta',
 'echo',
 'foxtrot',
 'golf',
 'hotel']
8 ['alpha',

Width is a target, not a promise. The formatter breaks lines between items, never inside one, so a single item longer than the width stays whole and its line runs long. Narrow widths suit side-by-side diffs and log files read on small screens; the default suits a normal terminal. Every other argument in this guide can combine with width, and the width counts the indentation of the level it is formatting, so deep values get less room per line than shallow ones.

sort_dicts: sorted keys or insertion order

Dict keys sort by default, at every level of the structure. Setting sort_dicts to false keeps the order the dict was built in, again at every level, as the nested record in the last call shows:

Python
import pprint
record = {"zebra": 1, "apple": 2, "mango": 3}
pprint.pprint(record)
pprint.pprint(record, sort_dicts=False)
nested = {"outer": {"z": 1, "a": 2}}
pprint.pprint(nested, sort_dicts=False)

The exact output:

Output
{'apple': 2, 'mango': 3, 'zebra': 1}
{'zebra': 1, 'apple': 2, 'mango': 3}
{'outer': {'z': 1, 'a': 2}}

Sorted output is the right default for inspection, because the eye finds a key in a sorted run faster than in a build order it has never seen. Insertion order is the right choice when the order itself carries meaning: a report whose sections must appear in a set sequence, or a record that mirrors a form. Keys that cannot be ordered against each other, such as a dict mixing strings and integers as keys, cannot be sorted, and the formatter falls back to the order it can produce rather than failing.

Depth: cut off the deep levels

Large structures bury the part that matters under levels no one needs. The depth argument limits how many levels the formatter opens; anything deeper is replaced by three dots in braces for a dict or in brackets for a list:

Python
import pprint
data = {"level1": {"level2": {"level3": {"level4": "deep"}}}}
pprint.pprint(data)
pprint.pprint(data, depth=1)
pprint.pprint(data, depth=2)
pprint.pprint([1, [2, [3, [4]]]], depth=2)

The exact output:

Output
{'level1': {'level2': {'level3': {'level4': 'deep'}}}}
{'level1': {...}}
{'level1': {'level2': {...}}}
[1, [2, [...]]]

A depth of 1 opens only the outer container. Depth suits a first look at data of unknown shape: print at a shallow depth to learn the outline, then print the one branch that matters in full. It also keeps a runaway structure, such as a parsed document with hundreds of nested nodes, from filling the screen. The cut changes only how the data looks; the data itself is untouched, and a later call without depth formats the whole value.

Compact: pack short items onto shared lines

Without compact, a list that does not fit the width puts one item on each line, which makes a list of twenty small numbers twenty lines tall. With compact set to true, the formatter packs as many items on each line as the width allows, for lists and for sequences of small containers alike:

Python
import pprint
nums = list(range(20))
pprint.pprint(nums, width=40)
pprint.pprint(nums, width=40, compact=True)
pairs = [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5), ("f", 6)]
pprint.pprint(pairs, width=30, compact=True)

The exact output:

Output
[0,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 10,
 11,
 12,
 13,
 14,
 15,
 16,
 17,
 18,
 19]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
 12, 13, 14, 15, 16, 17, 18, 19]
[('a', 1), ('b', 2), ('c', 3),
 ('d', 4), ('e', 5),
 ('f', 6)]

Compact is the setting that makes pprint output look like the data literals programmers write by hand. It changes lists and tuples of short items; a dict still puts one entry per line when it breaks, and an item too long for the remaining space starts a fresh line rather than splitting. For dense numeric or tabular data, compact at a terminal width is usually the most readable form the module produces.

PrettyPrinter: hold the settings, add underscores

When one program formats many values with the same settings, a PrettyPrinter object holds those settings once. Its constructor takes the same arguments as the functions, plus indent, the number of spaces each inner level steps in. One more function-level setting, underscore_numbers, groups the digits of long integers with underscores, the way Python literals allow:

Python
import pprint
data = {"name": "ada", "scores": [10, 20, 30, 40, 50], "city": "leeds"}
pprint.PrettyPrinter(width=40).pprint(data)
pprint.PrettyPrinter(width=40, indent=4).pprint(data)
print(pprint.pformat(1234567, underscore_numbers=True))
print(pprint.pformat(1234567))

The exact output:

Output
{'city': 'leeds',
 'name': 'ada',
 'scores': [10, 20, 30, 40, 50]}
{   'city': 'leeds',
    'name': 'ada',
    'scores': [10, 20, 30, 40, 50]}
1_234_567
1234567

The default indent is 1, which is why the first block aligns its entries one space in from the opening brace. An indent of 4 gives the stepped look of hand-written code. The underscore form suits printed reports of large counts, where the grouped digits are easier to read at a glance; it affects integers only, and only in the formatted text, never in the value itself.

The traps: long strings and recursive data

Trap
Two results surprise on first sight. A plain string is not a container, so pformat returns its quoted form on one line however long it runs. Hand that same string to pprint with a width and the output gains parentheses: the printer shows the string as an expression split across lines, a different text from the one-line form. And data that contains itself cannot be written out in full: the formatter marks the point where the value loops back with a recursion note that carries a memory address, so the exact text differs from run to run. The check below tests the shape of that line instead of its full text:
Python
import pprint
print(pprint.pformat("a very long single string that keeps going past the width"))
pprint.pprint("a very long single string that keeps going past the width", width=30)
loop = [1, 2]
loop.append(loop)
text = pprint.pformat(loop)
print(text.startswith("[1, 2, <Recursion on list"))
print(pprint.isrecursive(loop))
print(pprint.isreadable(loop))
print(pprint.isreadable([1, "two", 3.0]))

The exact output:

Output
'a very long single string that keeps going past the width'
('a very long single string '
 'that keeps going past the '
 'width')
True
True
False
True

The two helper functions answer the questions the trap raises. pprint.isrecursive reports whether a value contains a reference back to itself or to a container that holds it. pprint.isreadable reports whether the formatted form can be read back as a value with the same shape: a plain list of numbers and strings can, and a recursive list cannot, because its formatted form holds the recursion note instead of data. Code that stores formatted output for later reading should test isreadable first and fall back to another format, such as JSON, when the answer is false.

Which choice for which job

Job Choice Why
Read a nested value on screen pprint.pprint Sorted, broken across lines
Formatted text as a string pprint.pformat Same layout, ready to write or log
Fit a small screen or a diff width Lines break at the set length
Keep the build order of keys sort_dicts=False Insertion order at every level
First look at a deep structure depth Deeper levels shown as dots
Dense lists of short items compact=True Items share lines up to the width
Same settings for many values PrettyPrinter Settings and indent held once
Readable long integers underscore_numbers=True Digits grouped with underscores

Checklist

  • Reach for pformat when the formatted text goes to a file or a log, and pprint when it goes straight to the screen.
  • Set width for the place the output will be read; remember an item longer than the width still runs long.
  • Leave key sorting on for inspection, and turn it off only when the build order carries meaning.
  • Print at a shallow depth first when the shape of the data is unknown.
  • Turn compact on for lists of short items that would otherwise take one line each.
  • Test isreadable before storing formatted output that later code must read back.
  • Wrap long strings with a text formatter instead; a string is not a container and does not break like one.

Sources

  • Python Standard Library, pprint — pprint, pformat, PrettyPrinter, and the width, depth, compact, sort_dicts, and underscore_numbers settings, plus isrecursive and isreadable.

Keep Exploring