Python: Pretty print nested dictionaries – dict of dicts

In this article, we will discuss how to print a nested dictionary in a beautiful & readable format.

Table of Contents

A nested dictionary is a kind of dictionary, which contains other dictionaries object as values, which might also contains other dictionaries. For example,

students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City':  {  'perm': 'Tokyo', 
                                                                'current': 'London'
                                                                }},
            }

Our main dictionary students contains the information of students. Like keys are IDs of students and value fields are also dictionary objects, which contains the detail information of students like Name, Age and City. Now city value can also be an another dictionary. So, this is a three level nested dictionary. Now let’s see how to print this nested dictionary in pretty format,

Print a nested dictionary in pretty format

We have created few functions, that will iterate over all key-value pairs of dictionary with dictionaries and print them in an indented format. For example,

# A Nested dictionary i.e. dictionaty of dictionaries
students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City':  {  'perm': 'Tokyo', 
                                                                'current': 'London'
                                                                }},
            }

def print_nested_dict(dict_obj, indent = 0):
    ''' Pretty Print nested dictionary with given indent level  
    '''
    # Iterate over all key-value pairs of dictionary
    for key, value in dict_obj.items():
        # If value is dict type, then print nested dict 
        if isinstance(value, dict):
            print(' ' * indent, key, ':', '{')
            print_nested_dict(value, indent + 4)
            print(' ' * indent, '}')
        else:
            print(' ' * indent, key, ':', value)


def display_dict(dict_obj):
    ''' Pretty print nested dictionary
    '''
    print('{')
    print_nested_dict(dict_obj, 4)
    print('}')

display_dict(students)

Output:

{
     ID 1 : {
         Name : Shaun 
         Age : 35     
         City : Delhi 
     }
     ID 2 : {
         Name : Ritika
         Age : 31     
         City : Mumbai
     }
     ID 3 : {
         Name : Smriti
         Age : 33
         City : Sydney
     }
     ID 4 : {
         Name : Jacob
         Age : 23
         City : {
             perm : Tokyo
             current : London
         }
     }
}

It recursively iterated through all internal dictionaries and printed them with an incremental indent level.

Print a nested dictionary in pretty format using json module

Instead of writing our own functions, we can use the json module to print a dictionary of dictionaries in pretty fromat like json. For example,

import json as json

# A Nested dictionary i.e. dictionaty of dictionaries
students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City': {'perm': 'Tokyo', 'current': 'London'}},
            }

print(json.dumps(students, indent=4))

Output:

{
    "ID 1": {
        "Name": "Shaun",
        "Age": 35,
        "City": "Delhi"
    },
    "ID 2": {
        "Name": "Ritika",
        "Age": 31,
        "City": "Mumbai"
    },
    "ID 3": {
        "Name": "Smriti",
        "Age": 33,
        "City": "Sydney"
    },
    "ID 4": {
        "Name": "Jacob",
        "Age": 23,
        "City": {
            "perm": "Tokyo",
            "current": "London"
        }
    }
}

It is the most simpler solution.

Pretty print nested dictionary as a table in python

Using the pandas module, we can print the nested dictionary a table. For example,

import pandas as pd

students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City': 'Tokyo'}
            }

df = pd.DataFrame(students).T

print(df)

Output

        Name Age    City
ID 1   Shaun  35   Delhi
ID 2  Ritika  31  Mumbai
ID 3  Smriti  33  Sydney
ID 4   Jacob  23   Tokyo

Summary:

We learned abouth the two different ways to print a nested dictionary i.e a dictionary of dictionaries in pretty format like json.

Leave a Comment

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.

Scroll to Top