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:
import json
mydict = {'key1': ['value1', 'value2'], 'key2': {'value1': 4, 'value2': 5}}
print(json.dumps(mydict, sort_keys=True, indent=4))
This will produce output with tabbed indentation:
{ "key1": [ "value1", "value2" ], "key2": { "value1": 4, "value2": 5 } }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3