PythonMastery

Read nested data with pprint

print() puts a nested dict on one endless line. pprint.pp breaks it up by structure, and depth= and width= let you see the shape before the detail.

API responses, JSON files and config dicts are nested, and print() puts all of it on one line. pprint (pretty-print) lays the same data out by structure: one key per line, nested parts indented.

Before

python
order = {"id": "A-1001", "customer": {"name": "Ada", "email": "ada@example.com"},
         "items": [{"sku": "TEA-01", "qty": 2, "price": 4.5}, {"sku": "MUG-02", "qty": 1, "price": 9.0}],
         "status": "paid"}

print(order)
output
{'id': 'A-1001', 'customer': {'name': 'Ada', 'email': 'ada@example.com'}, 'items': [{'sku': 'TEA-01', 'qty': 2, 'price': 4.5}, {'sku': 'MUG-02', 'qty': 1, 'price': 9.0}], 'status': 'paid'}

After

python
from pprint import pp

order = {"id": "A-1001", "customer": {"name": "Ada", "email": "ada@example.com"},
         "items": [{"sku": "TEA-01", "qty": 2, "price": 4.5}, {"sku": "MUG-02", "qty": 1, "price": 9.0}],
         "status": "paid"}

pp(order)
output
{'id': 'A-1001',
 'customer': {'name': 'Ada', 'email': 'ada@example.com'},
 'items': [{'sku': 'TEA-01', 'qty': 2, 'price': 4.5},
           {'sku': 'MUG-02', 'qty': 1, 'price': 9.0}],
 'status': 'paid'}

Now you can see there are two items, and which keys each one has.

Shape first, then detail

On a big response, depth= hides everything below a level, so you see the outline before drowning in it. width= changes where lines break, and sort_dicts=True orders the keys so two dicts are easy to compare.

python
from pprint import pp

order = {"id": "A-1001", "customer": {"name": "Ada", "email": "ada@example.com"},
         "items": [{"sku": "TEA-01", "qty": 2, "price": 4.5}, {"sku": "MUG-02", "qty": 1, "price": 9.0}],
         "status": "paid"}

pp(order, depth=1)
print("---")
pp(order, width=100, sort_dicts=True)
output
{'id': 'A-1001', 'customer': {...}, 'items': [...], 'status': 'paid'}
---
{'customer': {'email': 'ada@example.com', 'name': 'Ada'},
 'id': 'A-1001',
 'items': [{'price': 4.5, 'qty': 2, 'sku': 'TEA-01'}, {'price': 9.0, 'qty': 1, 'sku': 'MUG-02'}],
 'status': 'paid'}

Why it works

pprint measures each part's printed length and only breaks a line when it would pass width (80 by default). It uses repr() for the values, so strings keep their quotes, which helps when debugging. pp (Python 3.8+) keeps your key order; the older pprint.pprint sorts keys unless you pass sort_dicts=False.

When not to use it

The output is Python syntax, not JSON: single quotes, True instead of true. When the result is going into a file or another program, use json.dumps(order, indent=2) instead; the CSV & JSON lesson covers it. And for a DataFrame, pandas prints its own tables.

Learn it properly: Dictionaries, CSV, JSON, and JSONL — Structured Text Done Right