Home >Backend Development >Python Tutorial >How to Pretty Print Nested Dictionaries in Python without losing Indentation?
Pretty Printing Nested Dictionaries
Pretty printing nested dictionaries in Python can be a challenge, especially when dealing with significant depth. While the pprint() module provides some functionality for formatting nested structures, it may not always produce the desired indentations.
Solution: Using the JSON Serializer
One effective solution is to leverage the JSON serializer's ability to format nested dictionaries. Here's an example:
<code class="python">import json data = {'a': 2, 'b': {'x': 3, 'y': {'t1': 4, 't2': 5}}} # Serialize and pretty print the dictionary json_string = json.dumps(data, sort_keys=True, indent=4) print(json_string)</code>
This code will generate a neatly formatted JSON representation of the dictionary, with 4 spaces of indentation for each level:
{ "a": 2, "b": { "x": 3, "y": { "t1": 4, "t2": 5 } } }
The above is the detailed content of How to Pretty Print Nested Dictionaries in Python without losing Indentation?. For more information, please follow other related articles on the PHP Chinese website!