How to pretty print nested dictionaries?
How can you pretty print nested dictionaries in Python to make them more readable? What tools or methods can help you display complex dictionary structures in an easy-to-understand format?
Pretty printing nested dictionaries in Python is a great way to make complex data structures more readable and easier to understand. When dictionaries contain other dictionaries (nested dictionaries), the default print output can be hard to follow because everything is shown in one long line.
How to Pretty Print Nested Dictionaries
Python provides a built-in module called pprint (pretty-print) that formats data structures like dictionaries in a clean, indented style.
Using pprint module:
import pprint
nested_dict = {
'name': 'Alice',
'details': {
'age': 30,
'city': 'New York',
'skills': ['Python', 'SQL', 'Machine Learning']
},
'projects': {
'project1': {'status': 'complete', 'budget': 10000},
'project2': {'status': 'in progress', 'budget': 15000}
}
}
pprint.pprint(nested_dict)
This will print the nested dictionary with proper indentation, line breaks, and spacing, making it much easier to read than the standard print() function.
Benefits of using pprint:
- Automatically adds indentation for nested structures.
- Breaks lines logically so each item is clear.
- Makes debugging and data inspection simpler.
Alternative methods:
JSON module: You can convert the dictionary to a JSON string with indentation.
import json
print(json.dumps(nested_dict, indent=4))
This works well especially if you want a format that’s easily shared or logged.
Summary:
- Use pprint.pprint() for quick, readable output inside Python.
- Use json.dumps() if you want nicely formatted JSON output.
- Both methods greatly improve readability for nested dictionaries.
Pretty printing helps you visually parse data better and is especially useful when debugging or presenting data.