Anyone who knows the basics of python are familiar with print() function. The purpose is very simple, it is for printing anything in python.

pprint() function also has similar functionality. But the only difference is in the way it prints complex data structures. The normal print() function prints the entire content in a single line. This is fine if the printed content is small in length and is not a complex data structure. But the output will become difficult to read if the content is a complex data structure like a complex json or a long content.

I will demonstrate the differences using an example. The program is given below. In this program, I am printing a JSON using print() and pprint() functions.

from pprint import pprint
sample_json = {
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
print(sample_json)
pprint(sample_json)

The output of print() function is given below. The JSON got printed in a single line which is a very long text and not properly readable.

The output of pprint() function is given below. The JSON got printed in multiple lines in a much formatted and readable way compared to the one printed by print() function.

I hope the explanation is clear.

Advertisement