How to Pretty Print Nested Dictionaries in Python without losing Indentation?

Patricia Arquette
Release: 2024-10-23 18:20:22
Original
512 people have browsed it

How to Pretty Print Nested Dictionaries in Python without losing Indentation?

Pretty Printing Nested Dictionaries

Pretty printing nested dictionaries in Python can be a challenge, especially when dealing with significant depth. While the pprint() module provides some functionality for formatting nested structures, it may not always produce the desired indentations.

Solution: Using the JSON Serializer

One effective solution is to leverage the JSON serializer's ability to format nested dictionaries. Here's an example:

<code class="python">import json

data = {'a': 2, 'b': {'x': 3, 'y': {'t1': 4, 't2': 5}}}

# Serialize and pretty print the dictionary
json_string = json.dumps(data, sort_keys=True, indent=4)
print(json_string)</code>
Copy after login

This code will generate a neatly formatted JSON representation of the dictionary, with 4 spaces of indentation for each level:

{
    "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 in Python without losing 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!