Use pprint for Nested Structure Debug Output in Python
Pretty-print nested dictionaries and lists with pprint for readable, organized debug output.
Python code
25 linesfrom 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
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
- Use `pprint.pp(data, indent=4, width=100)` for tighter or wider output
- 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
More from Errors & debugging
- Catch RecursionError and Fail Gracefully in Python easy
- Catch ValueError and print friendly message in Python easy
- Collect Multiple Validation Errors in Python Before Raising medium
- Handle ValueError and ZeroDivisionError in Python with try except easy
- How to Add a Correlation ID to Logging Records in Python medium
- How to Assert Preconditions with Descriptive Messages in Python easy
Keep learning
Related tutorials and quizzes for this topic.