How to Print Nested Python Dictionaries with Indentation?

Barbara Streisand
Release: 2024-10-24 05:39:30
Original
415 people have browsed it

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

This will produce output with tabbed indentation:

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

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!

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!