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

Mary-Kate Olsen
Release: 2024-10-23 18:15:01
Original
554 people have browsed it

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template