Skip to content

Python pretty print dict | Example code

  • by

Use json.dumps() to Pretty Print a Dictionary in Python. Thie function will convert a Python object into a JSON string.

The dumps() function accepts 3 parameters used for pretty-printing: the object for conversion, a boolean value sort_keys, which determines whether the entries should be sorted by key, and an indent, which specifies the number of spaces for indentation.

Python pretty print dict example

A simple example code import JSON module use dumps() function.

import json

dct_arr = [
    {'Name': 'John', 'Age': '16', 'Country': 'USA'},
    {'Name': 'Jose', 'Age': '20', 'Country': 'Spain'},
]

print(json.dumps(dct_arr, sort_keys=False, indent=4))

Output:

Python pretty print dict

How do pretty print nested dictionaries?

Answer: If you have a dictionary with more than a few items you need to be able to read, the json.dumps() function takes an indent the argument that automatically formats things legibly for you:

import json

...

print json.dumps(my_dict, indent=1)

Do comment if you have any doubts or suggestions on this Python pretty print topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading