Home  >  Article  >  Backend Development  >  How to Pretty Print Nested Dictionaries with Customized Indentation in Python?

How to Pretty Print Nested Dictionaries with Customized Indentation in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 18:15:01484browse

How to Pretty Print Nested Dictionaries with Customized Indentation in Python?

Pretty Printing Nested Dictionaries in Python

Pretty printing is a crucial aspect of debugging and visualizing complex data structures like nested dictionaries. While Python's standard pprint module can handle basic pretty printing, it may not always provide the desired indentation for deeply nested structures.

A clever approach to tackling this issue is to leverage the JSON serializer. As JSON is designed to handle nested data, it offers a robust mechanism for pretty printing complex structures. By leveraging the sort_keys and indent parameters, we can customize the indentation to our liking:

<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))

# Output:
{
    "a": 2,
    "b": {
        "x": 3,
        "y": {
            "t1": 4,
            "t2": 5
        }
    }
}</code>

This solution provides a concise and effective method for pretty printing nested dictionaries, catering to the need for clear and visually appealing output.

The above is the detailed content of How to Pretty Print Nested Dictionaries with Customized Indentation in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn