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)
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}
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!"
# }
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)
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}
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!"
# }