0

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)

Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • How about printing it in JSON format, such as: https://stackoverflow.com/questions/36021332/how-to-prettyprint-human-readably-print-a-python-dict-in-json-format-double-q – Fiddling Bits Aug 17 '22 at 15:25
  • The built-in pprint library may help: https://docs.python.org/3/library/pprint.html – jjramsey Aug 17 '22 at 15:26
  • [Please don't post images of text.](//meta.stackoverflow.com/q/285551) Include it as a [formatted code block](/help/formatting) instead of an image. – Pranav Hosangadi Aug 17 '22 at 16:56
  • I removed the javascript and nodejs tags because your question isn't really about those things, it is about how to get python to output dictionaries in a certain format – Pranav Hosangadi Aug 17 '22 at 16:57
  • See also `devtools.debug` (3rd party) – 2e0byo Aug 17 '22 at 21:53

2 Answers2

1

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}
0

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!"
# }
Artie Vandelay
  • 436
  • 2
  • 10