Python Pretty Print List of Dictionaries Example

By Hardik Savani October 30, 2023 Category : Python

Hello Dev,

I am going to show you an example of python pretty print list of dictionaries. This example will help you python pretty print dictionary as json. you will learn python dictionary pretty print. I explained simply about python pretty print nested dictionary. Here, Create a basic example of python pretty print list example.

In you want to display dictionary in proper format from string in python then i will give you two examples to do pretty print list of dictionaries in python language. first we will use json.dumps() and second one will use pprint.pprint() function. So, without further ado, let's see simple examples: You can use these examples with python3 (Python 3) version.

Example 1: Python Pretty Print Dictionary using json.dumps()

main.py

import json

# Create New Json
myList = [{"id": 1,"name": "Hardik"}, {"id": 2,"name": "Vimal"}, {"id": 3,"name": "Harshad"}]

# Display JSON with Prettyprint
print(json.dumps(myList, sort_keys=False, indent=4))

Output:

[
    {
        "id": 1,
        "name": "Hardik"
    },
    {
        "id": 2,
        "name": "Vimal"
    },
    {
        "id": 3,
        "name": "Harshad"
    }
]

Example 2: Python Pretty Print Dictionary using pprint.pprint()

main.py

import pprint

# Create New Json
myList = [{"id": 1,"name": "Hardik"}, {"id": 2,"name": "Vimal"}, {"id": 3,"name": "Harshad"}]

# Display JSON with Prettyprint
pprint.pprint(myList)

Output:

[{'id': 1, 'name': 'Hardik'},
 {'id': 2, 'name': 'Vimal'},
 {'id': 3, 'name': 'Harshad'}]

I hope it can help you...

Tags :
Shares