Use pprint for Nested Structure Debug Output in Python

Pretty-print nested dictionaries and lists with pprint for readable, organized debug output.

Easy Python 3.9+ Aug 9, 2026 Errors & debugging 15 views 0 copies

Python code

25 lines
Python 3.9+
from pprint import pprint

def build_nested_structure():
    """Create a sample nested data structure for demonstration."""
    return {
        "project": "DataPipeline",
        "config": {
            "inputs": ["raw_1.json", "raw_2.json"],
            "processing": {
                "steps": ["clean", "transform", "validate"],
                "parameters": {
                    "clean": {"strategy": "remove_empty", "min_len": 3},
                    "transform": {"decimal_places": 2},
                    "validate": {"schema_version": "2.1.0", "strict": True}
                }
            }
        },
        "output": {"format": "parquet", "compression": "snappy"}
    }


if __name__ == "__main__":
    data = build_nested_structure()
    print("Pretty-printed nested structure:")
    pprint(data, indent=2, width=50, sort_dicts=True)

Output

stdout
Pretty-printed nested structure:
{ 'config': { 'inputs': ['raw_1.json',
                        'raw_2.json'],
               'processing': { 'parameters': { 'clean': { 'min_len': 3,
                                                          'strategy': 'remove_empty'},
                                                 'transform': { 'decimal_places': 2},
                                                 'validate': { 'schema_version': '2.1.0',
                                                               'strict': True}},
                                'steps': ['clean', 'transform', 'validate']}},
  'output': {'compression': 'snappy', 'format': 'parquet'},
  'project': 'DataPipeline'}

How it works

The pprint module formats nested data structures with indentation, line wrapping, and sorted keys (when sort_dicts=True), making complex output much easier to scan. Parameters like indent and width control the layout: indent sets the nested indentation level, while width caps line length causing long lists and dictionaries to break cleanly across lines. pprint recursively walks the structure, so deeply nested dictionaries and lists are handled consistently. This makes it ideal for debugging logs and inspecting API responses where you need to see the full shape of the data.

Common mistakes

  • Using `print()` on a nested dict, which outputs a single unreadable line
  • Forgetting `sort_dicts=True` when you want deterministic key order across runs
  • Setting `width` too high, so long values still overflow and defeat the purpose
  • Applying `pprint.pp()` without arguments and wondering why layout looks different than expected

Variations

  1. Use `pprint.pp(data, indent=4, width=100)` for tighter or wider output
  2. Use `pprint.pformat(data)` to capture the formatted string and reuse it in logs

Real-world use cases

  • Debugging a JSON response from an API, showing nested fields and lists clearly during development.
  • Inspecting configuration dictionaries loaded from YAML files to verify structure before processing.
  • Logging complex state of a data pipeline job to trace issues in transformation steps.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Errors & debugging

Related tutorials and quizzes for this topic.