DEV Community

pprint (Pretty Printer) in Python

importox on June 09, 2020

In this Python tutorial, you are going to learn about a very useful inbuilt module in python that is called pprint(). pprint is a python module th...
Collapse
 
waylonwalker profile image
Waylon Walker • Edited

I love the simplicity of using pprint to make things like dictionary printouts so much easier to read. If its something that you are using very often you can add color fairly easy, but it does take quite a few more lines than pprint.

from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers import JsonLexer
import json


dictionary = {"id": 1,"name": "Leanne Graham","username": "Bret","email": "Sincere@april.biz","address": {  "street": "Kulas Light",  "suite": "Apt. 556",  "city": "Gwenborough",  "zipcode": "92998-3874",  "geo": {    "lat": "-37.3159",    "lng": "81.1496"  }},"phone": "1-770-736-8031 x56442","website": "hildegard.org","company": {  "name": "Romaguera-Crona",  "catchPhrase": "Multi-layered client-server neural-net",  "bs": "harness real-time e-markets"}}


print(
    highlight(
        json.dumps(dictionary, sort_keys=True, indent=2,),
        JsonLexer(),
        TerminalFormatter(),
    )
)

Not nearly as simple, but more readable.