Home >Backend Development >Python Tutorial >How to Pretty Print Nested Dictionaries with Custom Indentation Using JSON?
Pretty Printing Nested Dictionaries
When working with Python dictionaries, displaying their contents in a clear and organized manner can be essential. However, built-in pretty printing methods like pprint() may not provide the desired indentation for deeply nested dictionaries.
One approach to achieve the desired indentation is to leverage the JSON serializer, which inherently handles nested structures:
<code class="python">import json mydict = {'a': 2, 'b': {'x': 3, 'y': {'t1': 4, 't2': 5}}} print(json.dumps(mydict, sort_keys=True, indent=4))</code>
This will generate output formatted with indentation for each nesting level:
<code class="json">{ "a": 2, "b": { "x": 3, "y": { "t1": 4, "t2": 5 } } }</code>
By utilizing the JSON serializer, you can conveniently pretty print nested dictionaries with the desired indentation and maintain the order of keys in the output.
The above is the detailed content of How to Pretty Print Nested Dictionaries with Custom Indentation Using JSON?. For more information, please follow other related articles on the PHP Chinese website!