How to format python dictionary print output like JavaScript?

Question:

I’m new to Python but come from JavaScript
and I was trying to print an object/dictionary to terminal by using print(vars(client)) but came out unformatted like this.

I’m used to Node JS terminal outputs and was wondering how I can format the Python output like in JS.

I printed out this using a similar Node module in JavaScript (I’m using the vscode terminal)

Asked By: Dawit Mengistie

||

Answers:

There is a pprint library which can be used to print dictionary output in a formatted way. Here is an example:

import pprint
dictionary = {"foo": 1, "bar": 2}
pprint.pprint(dictionary)

Output:

{'bar': 2, 'foo': 1}
Answered By: eq321

If you need it to be actually compatible with other JSON parsers, use the json module. It takes care of special cases like None correctly becoming null, enforcing doubly-quoted strings etc.

import json
d = {"foo": None, "bar": "Hello world!"}
print(json.dumps(d, indent=4))
# {
#     "foo": null,
#     "bar": "Hello world!"
# }
Answered By: Artie Vandelay
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.