Home  >  Article  >  Backend Development  >  How to Pretty Print Nested Dictionaries in Python without losing Indentation?

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-23 18:20:22497browse

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>

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

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!

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