. Advertisement .
..3..
. Advertisement .
..4..
Python has a lot of packages to work with dictionaries, but still, there is a need for a Python programmer to know how to pretty print a dictionary. There are many ways to do this with a dictionary. Once you have a dictionary tree, you can use a method to convert the dictionary tree into a string. This blog will cover the different methods to pretty print a dictionary in Python.
Pretty Print a Dictionary in Python
In Python, simply use the pprint() command to pretty print a dictionary. So, without wasting any time, let’s take a look at the following example:
import pprint arrdct1 = [{'name':'aarti','subject':'physics','marks':'86'}, {'name':'trusha','subject':'chemistry','marks':'98'}, {'name':'meet','subject':'maths','marks':'78'}, {'name':'rohan','subject':'biology','marks':'92'} ] pprint.pprint(arrdct1)
Result:
[{'marks': '86', 'name': 'aarti', 'subject': 'physics'}, {'marks': '98', 'name': 'trusha', 'subject': 'chemistry'}, {'marks': '78', 'name': 'meet', 'subject': 'maths'}, {'marks': '92', 'name': 'rohan', 'subject': 'biology'}]
Option 1: Utilize pprint()
In Python, simply use the pprint() command to pretty print a dictionary. So, without wasting any time, let’s take a look at the following example:
import pprint arrdct1 = [ {'name':'aarti','subject':'physics','marks':'86'}, {'name':'trusha','subject':'chemistry','marks':'98'}, {'name':'meet','subject':'maths','marks':'78'}, {'name':'rohan','subject':'biology','marks':'92'} ] pprint.pprint(arrdct1)
Result:
[{'marks': '86', 'name': 'aarti', 'subject': 'physics'},
{'marks': '98', 'name': 'trusha', 'subject': 'chemistry'},
{'marks': '78', 'name': 'meet', 'subject': 'maths'},
{'marks': '92', 'name': 'rohan', 'subject': 'biology'}]
Option 2: Utilize json.dumps()
In Python, simply utilize the json.dumps() command to pretty print a dictionary. It turns strings into json strings json formate. So, without wasting any time, let’s take a look at the following example:
import json arrdct1 = [ {'name':'aarti','subject':'physics','marks':'86'}, {'name':'trusha','subject':'chemistry','marks':'98'}, {'name':'meet','subject':'maths','marks':'78'}, {'name':'rohan','subject':'biology','marks':'92'} ] print(json.dumps(arrdct1, sort_keys=False, indent=4))
Result:
[
{
"name": "aarti",
"subject": "physics",
"marks": "86"
},
{
"name": "trusha",
"subject": "chemistry",
"marks": "98"
},
{
"name": "meet",
"subject": "maths",
"marks": "78"
},
{
"name": "rohan",
"subject": "biology",
"marks": "92"
}
]
Conclusion
We hope our blog post on “tips on pretty print a Dictionary in Python” was useful. With this information, you should be able to handle this issue and a slew of other concerns when you design your application.
Please leave a comment if you want to learn more about the topic or if you have any questions or ideas to share. Thank you for taking the time to read this!
Leave a comment