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

How to Pretty Print Nested Dictionaries with Indentation?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 04:00:31961browse

How to Pretty Print Nested Dictionaries with Indentation?

Pretty Printing Nested Dictionaries

Problem

You want to prettify a deeply nested Python dictionary with an indentation for each level, achieving an output like:

key1
    value1
    value2
    key2
       value1
       value2

However, pprint.PrettyPrinter() alone does not provide the desired output.

Solution

The JSON serializer can effectively handle nested dictionaries. Here's how you can leverage it:

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

Output:

{
    "a": 2,
    "b": {
        "x": 3,
        "y": {
            "t1": 4,
            "t2": 5
        }
    }
}

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