How to Pretty Print Nested Dictionaries with Indentation?

Patricia Arquette
Release: 2024-10-24 04:00:31
Original
973 people have browsed it

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

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

Output:

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!