How to pretty print a dictionary in Python within a terminal?

There’s a built-in module in Python called pprint it allows you to “pretty print” data structures in Python. To use it import the module, and wrap anything you want to print with pprint instead of print.

import pprint

d = {
    'name': 'paul',
    'job': 'swe',
    'likes': ['coffee', 'tea', 'rice']
}

# using pprint
pprint.pprint(d, width=2)

Remember to force width if you have a dictionary that fits on a single line. From the docs

Single line dictionaries stay as a single line.

The formatted representation keeps objects on a single line if it can, and breaks them onto multiple lines if they don’t fit within the allowed width. Construct PrettyPrinter objects explicitly if you need to adjust the width constraint.

Published by Paul Young-Suk Lee

SWE @lyft. Currently working on data infrastructure

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: