Python: Pretty Print Nested Dictionaries – Dict of Dicts

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

To an infinite depth, a dictionary may include another dictionary, which can contain dictionaries, and so on. This is referred to as a nested dictionary.

Nested dictionaries are one among several ways during which structured information is represented (similar to records or structures in other languages).

In this article, we’ll look at how to print a nested dictionary in a visually beautiful and readable format.

Examples:

Input:

nesteddict = {
'hello': {'www': 100, 'yyy': 'Helloworld'},
'this': {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
'BTechGeeks': {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}

Output:

{
    "hello": {
        "www": 100,
        "yyy": "Helloworld"
    },
    "this": {
        "www": "vikram",
        "age": 20,
        "DOB": "FEB"
    },
    "BTechGeeks": {
        "PLACE": "HYDERABAD",
        "PINCODE": 500000,
        "PYTHON": {
            "FUNCTIONS": "Built in",
            "year": 1999
        }
    }
}

Print nested dictionaries in pretty way

There are several ways to print nested dictionaries in pretty way some of them are:

1)Using generic function

We can only call the values() function of a dictionary for a normal dictionary to get an iterable sequence of values. However, a value can be another dictionary object in a nested dictionary. To do this, we need to call the values() function again and get a new iterative sequence of values and search for dictation objects in those values. This is possible with recurrence in a simple way.

To print all of the key-values in this dictionary, we wrote a function that will recursively go through the nested dictionary and print all of the key-values.

Below is the implementation:

def printNested(nesteddict):
    # Traverse the dictionary
    for key, value in nesteddict.items():
        # If the value is of the dictionary type, then print
        # all of the key and values within the nested dictionary.
        if isinstance(value, dict):
            print(key, "  : {\n")
            printNested(value)
            print("\n}\n")

        else:
            print("\t", key, " : ", value)


# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
# passing nested dictionary to printNested Function
printNested(nesteddict)

Output:

hello   : {

	 www  :  100
	 yyy  :  Helloworld

}

this   : {

	 www  :  vikram
	 age  :  20
	 DOB  :  FEB

}

BTechGeeks   : {

	 PLACE  :  HYDERABAD
	 PINCODE  :  500000
PYTHON   : {

	 FUNCTIONS  :  Built in
	 year  :  1999

}
}

2)Using json module

Rather than writing our own functions, we can use the json module to print a dictionary of dictionaries in a format that looks like json.

Below is the implementation:

import json as json
# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
# using json to print the nested dict
print(json.dumps(nesteddict, indent=4))

Output:

{
    "hello": {
        "www": 100,
        "yyy": "Helloworld"
    },
    "this": {
        "www": "vikram",
        "age": 20,
        "DOB": "FEB"
    },
    "BTechGeeks": {
        "PLACE": "HYDERABAD",
        "PINCODE": 500000,
        "PYTHON": {
            "FUNCTIONS": "Built in",
            "year": 1999
        }
    }
}

3)Using pandas to print as table

We can print the nested dictionary a table using the pandas module.

Below is the implementation:

import pandas as pd
# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
print(pd.DataFrame(nesteddict).T)

Output:

                         DOB            PINCODE      PLACE        ...     age      www       yyy
hello                 NaN            NaN              NaN           ...     NaN    100         Helloworld
this                   FEB              NaN              NaN           ...     20        vikram    NaN
BTechGeeks      NaN            500000         HYDERABAD ... NaN      NaN        NaN

[3 rows x 7 columns]

 

 
Related Programs: