Pretty print dictionaries or another data in Python tricks


Supposed we have a nested dictionary. We want to print the data inside dictionary in decent format. Example, we have dictionary:

1
a = {1: ‘Hello’, 2: ‘World’, 3: {1: "Python", 2: "C++"}}

We usually print this using print() and showing exact format. There is some trick to pretty print this data using JSON.
Wait, JSON? yes, we will convert this data into JSON and print with indentation, like:

1
2
3
4
import json

a = {1: ‘Hello’, 2: ‘World’, 3: {1: "Python", 2: "C++"}}
print(json.dumps(a, indent=4))

This will give us results:

1
2
3
4
5
6
7
8
{
    "1": "Hello",
    "2": "World",
    "3": {
        "1": "Python",
        "2": "C++"
    }
}

Nice right? 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.