Home >Backend Development >Python Tutorial >How to Pretty Print Nested Dictionaries with Custom Indentation Using JSON?

How to Pretty Print Nested Dictionaries with Custom Indentation Using JSON?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 17:49:02675browse

How to Pretty Print Nested Dictionaries with Custom Indentation Using JSON?

Pretty Printing Nested Dictionaries

When working with Python dictionaries, displaying their contents in a clear and organized manner can be essential. However, built-in pretty printing methods like pprint() may not provide the desired indentation for deeply nested dictionaries.

One approach to achieve the desired indentation is to leverage the JSON serializer, which inherently handles nested structures:

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

This will generate output formatted with indentation for each nesting level:

<code class="json">{
    "a": 2,
    "b": {
        "x": 3,
        "y": {
            "t1": 4,
            "t2": 5
        }
    }
}</code>

By utilizing the JSON serializer, you can conveniently pretty print nested dictionaries with the desired indentation and maintain the order of keys in the output.

The above is the detailed content of How to Pretty Print Nested Dictionaries with Custom Indentation Using JSON?. 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