If you prefer to pretty print to a string instead of directly to the console, you can use the pprint.pformat() function:
import pprint websites = {'name': 'Pakainfo', 'age': 8, 'city': 'New York'} pretty_string = pprint.pformat(websites) print(pretty_string)
This will print the formatted dictionary as a string, allowing you to manipulate it or print it wherever you need.
Example 1: Using json.dumps()
main.py
import json # Create New Json websites = [{"id": 1,"name": "Pakainfo"}, {"id": 2,"name": "Yttags"}, {"id": 3,"name": "Pixmn"}] # Display JSON with Prettyprint print(json.dumps(websites, sort_keys=False, indent=4))
Result:
[ { "id": 1, "name": "Pakainfo" }, { "id": 2, "name": "Yttags" }, { "id": 3, "name": "Pixmn" } ]
Example 2: Using pprint.pprint()
To pretty print a dictionary in Python, you can use the pprint module (pretty-printing). Here’s how you can do it:
main.py
import pprint # Create New Json websites = [{"id": 1,"name": "Pakainfo"}, {"id": 2,"name": "Yttags"}, {"id": 3,"name": "Pixmn"}] # Display JSON with Prettyprint pprint.pprint(websites)
This will print the dictionary in a more readable format, where each key-value pair is printed on a separate line and the dictionary is indented properly.
Result:
[{'id': 1, 'name': 'Pakainfo'}, {'id': 2, 'name': 'Yttags'}, {'id': 3, 'name': 'Pixmn'}]