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)

5
  • How about printing it in JSON format, such as: stackoverflow.com/questions/36021332/… Commented Aug 17, 2022 at 15:25
  • The built-in pprint library may help: docs.python.org/3/library/pprint.html Commented Aug 17, 2022 at 15:26
  • Please don't post images of text. Include it as a formatted code block instead of an image. Commented Aug 17, 2022 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 Commented Aug 17, 2022 at 16:57
  • See also devtools.debug (3rd party) Commented Aug 17, 2022 at 21:53

2 Answers 2

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}
Sign up to request clarification or add additional context in comments.

1 Comment

you might want to add an example of the actual output
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!"
# }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.