Python pretty print dict | Example code

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 indent, which specifies the number of spaces for indentation.

Python pretty print dict example

Simple example code import JSON module use dumps() funciton.

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


Python pretty print dict

How to 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 and suggestions on this Python pretty print topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.