Home >Backend Development >Python Tutorial >How to Print Nested Python Dictionaries with Indentation?
Printing Nested Dictionaries with Indentation
Python's pprint module provides a convenient pprint() function for printing data structures in a readable format. However, it does not indent nested structures by default.
Solution Using JSON Serializer
One approach is to take advantage of the JSON serializer's ability to handle nested data. By dumping the dictionary to JSON and then printing the result using the indent parameter, you can achieve the desired indentation. Here's how:
<code class="python">import json mydict = {'key1': ['value1', 'value2'], 'key2': {'value1': 4, 'value2': 5}} print(json.dumps(mydict, sort_keys=True, indent=4))</code>
This will produce output with tabbed indentation:
{ "key1": [ "value1", "value2" ], "key2": { "value1": 4, "value2": 5 } }
The above is the detailed content of How to Print Nested Python Dictionaries with Indentation?. For more information, please follow other related articles on the PHP Chinese website!