"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Print Nested Python Dictionaries with Indentation?

How to Print Nested Python Dictionaries with Indentation?

Published on 2024-11-24
Browse:453

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:

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
    }
}
Release Statement This article is reprinted at: 1729674470 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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