Home >Backend Development >Python Tutorial >How to Print Nested Python Dictionaries with Indentation?

How to Print Nested Python Dictionaries with Indentation?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 05:39:30522browse

How to Print Nested Python Dictionaries with Indentation?

Printing Nested Dictionaries with Indentation

Python's pprint module provides a convenient pprint() function for printing data structures in a readable format. However, it does not indent nested structures by default.

Solution Using JSON Serializer

One approach is to take advantage of the JSON serializer's ability to handle nested data. By dumping the dictionary to JSON and then printing the result using the indent parameter, you can achieve the desired indentation. Here's how:

<code class="python">import json

mydict = {'key1': ['value1', 'value2'], 'key2': {'value1': 4, 'value2': 5}}

print(json.dumps(mydict, sort_keys=True, indent=4))</code>

This will produce output with tabbed indentation:

{
    "key1": [
        "value1",
        "value2"
    ],
    "key2": {
        "value1": 4,
        "value2": 5
    }
}

The above is the detailed content of How to Print Nested Python 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