Python provides pprint module that helps display complex data structures in a readable format. The pprint.pp function prints objects with formatting that improves readability, especially when working with nested dictionaries and lists.
By default, pprint.pp fits as much as possible within the available line width. For dictionaries containing multiple fields or nested values, the result can remain dense and harder to scan. For example, a configuration dictionary can be printed using the default formatting:
import pprint
config = {
'name': 'web-server',
'hosts': ['alpha', 'beta', 'gamma'],
'limits': {'cpu': 2, 'memory': '512M'},
}
pprint.pp(config)
Output:
{'name': 'web-server',
'hosts': ['alpha', 'beta', 'gamma'],
'limits': {'cpu': 2, 'memory': '512M'}}
Since Python 3.15, pprint.pp accepts an expand parameter that places opening and closing brackets on separate lines.
import pprint
config = {
'name': 'web-server',
'hosts': ['alpha', 'beta', 'gamma'],
'limits': {'cpu': 2, 'memory': '512M'},
}
pprint.pp(config, expand=True)
Output:
{
'name': 'web-server',
'hosts': ['alpha', 'beta', 'gamma'],
'limits': {'cpu': 2, 'memory': '512M'},
}
The opening brace is followed by a newline, every entry sits at the same indentation level, the closing brace stands on its own line, and the final entry gains a trailing comma.
Leave a Comment
Cancel reply