Open In App

Python | Pretty Print a dictionary with dictionary value

This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let’s code a way to perform this particular task in Python

Example



Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}
Output: gfg: 
           remark: good
           rate: 5
        cs: 
           rate: 3

Print Dictionary in Python

Let us see a few ways we can pretty print Dictionary in Python whose values are also a dictionary.

Create a Dictionary

In this example the code defines a nested dictionary named `test_dict` and prints its original structure. The dictionary has keys ‘gfg’ and ‘cs’, with associated inner dictionaries containing ‘rate’ and ‘remark’ keys.






# Python3 code to demonstrate working of
# Pretty Print a dictionary with dictionary value
# Using loops
 
# initializing dictionary
test_dict = {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))

Output :

The original dictionary is : {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}

Pretty Print a Dictionary in Python using Nested For Loops

In this approach, we just nested for loop through each dictionary element and its corresponding values using a brute manner.

Example : In this example the below code uses loops to pretty print the content of a nested dictionary (`test_dict`). It iterates through the keys of the outer dictionary and then through the keys and values of the nested dictionaries, printing them in a structured format.




# using loops to Pretty Print
print("The Pretty Print dictionary is : ")
for sub in test_dict:
    print(sub)
    for sub_nest in test_dict[sub]:
        print(sub_nest, ':', test_dict[sub][sub_nest])

Output:

The original dictionary is : {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
The Pretty Print dictionary is : 
gfg
rate : 5
remark : good
cs
rate : 3

Time Complexity: O(m*n) where m is the number of keys in the outer dictionary and n is the number of keys in the inner dictionary.
Auxiliary Space: O(1)

Print a Dictionary in Python using Tuple

Iterate through a Python dictionary’s items using a loop, converting each key-value pair into a tuple. Print the resulting tuples to represent the dictionary using tuples.

Example : In this example the below code iterates through items in the dictionary `test_dict`, converting each key-value pair into a tuple, and then prints the resulting tuples.




# convert dictionary items to tuples and print
for key, value in test_dict.items():
    print((key, value))

Output :

The original dictionary is :
('gfg', {'rate': 5, 'remark': 'good'})
('cs', {'rate': 3})

Time Complexity: O(n)
Auxiliary Space: O(1)

Print Dictionary in Python using Recursion and String Concatenation

In this method, we will create a recursive function that will be used to print a dictionary in Python. Inside the function, a for loop iterates each element of the dictionary. Inside the loop, the function appends a string to res using the += operator. The current value is a dictionary, the function calls itself recursively with the inner dictionary and an incremented indent value. The recursive call will have to traverse through all the items in the nested dictionary. Finally, the function returns the resulting string res.

Example : In this example the below code defines a function, `pretty_print_dict`, to recursively format a dictionary with proper indentation. It is then applied to `test_dict`, and the result is printed as a readable representation of the dictionary with nested structures.




def pretty_print_dict(d, indent=0):
    res = ""
    for k, v in d.items():
        res += "\t"*indent + str(k) + "\n"
        if isinstance(v, dict):
            res += pretty_print_dict(v, indent+1)
        else:
            res += "\t"*(indent+1) + str(v) + "\n"
    return res
 
 
test_dict = {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
 
# Using recursion and string concatenation for Pretty Print
print("The Pretty Print dictionary is : ")
print(pretty_print_dict(test_dict))
# This code is contributed by Jyothi pinjala.

Output:

The Pretty Print dictionary is : 
gfg
    rate
        5
    remark
        good
cs
    rate
        3

Time Complexity: O(N) Auxiliary Space: O(N)

Print Dictionary in Python using For Loop + Dictionary

For this, we will use a for loop to iterate over the keys and values of the dictionary. For each key-value pair, add the key to the string followed by a colon and a space. For each value, add it to the string followed by a newline character. Then return the pretty-printed dictionary string.

Example : In this example the below code function `pretty_print_dict` formats a nested dictionary by adding proper indentation and line breaks. The provided example dictionary is then printed in the formatted style for improved readability.




def pretty_print_dict(d):
    #take empty string
    pretty_dict = '' 
     
    #get items for dict
    for k, v in d.items():
        pretty_dict += f'{k}: \n'
        for value in v:
            pretty_dict += f'    {value}: {v[value]}\n'
    #return result
    return pretty_dict
 
d = {'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}
print(d)
print(pretty_print_dict(d))

Output:

{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}
gfg: 
    remark: good
    rate: 5
cs: 
    rate: 3

Time Complexity: O(n^2), where n is the number of key-value pairs in the dictionary.
Auxiliary Space: O(n), where n is the number of key-value pairs in the dictionary

Print Dictionary in Python using the pprint Module

The pprint module is a built-in module in Python that provides a way to pretty-print arbitrary Python data structures in a form that can be used as input to the interpreter. It is useful for debugging and displaying complex structures.




# import the pprint module
import pprint
 
# initialize the dictionary
test_dict = {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
 
# pretty-print the dictionary
print("The pretty-printed dictionary is:")
pprint.pprint(test_dict)

Output:

The pretty-printed dictionary is:
{'cs': {'rate': 3}, 'gfg': {'rate': 5, 'remark': 'good'}}

Time Complexity : Depends on the size of the input dictionary.
Space Complexity : Dependent on the size of the input dictionary.

Print Dictionary in Python using built-in Format

This method utilizes Python's `format` function to iterate through a dictionary (`my_dict`), printing each key-value pair with a customized template. Placeholders `{}` are replaced by the corresponding key and value, creating a tailored representation for each pair.

Example : In this exaple the below code initializes a nested dictionary (`test_dict`), prints it, and then iterates through its items using the `format` function to print key-value pairs with a customized template.




# Print the dictionary using format function
for key, value in my_dict.items():
    print("{}: {}".format(key, value))

Output :

The original dictionary is : {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
gfg: {'rate': 5, 'remark': 'good'}
cs: {'rate': 3}

Time Complexity: O(N) Auxiliary Space: O(N)

Pretty Print Dictionary in Python using the built-in JSON Module

Here we will use Python’s inbuilt JSON module to print a dictionary. We will be using the json.dumps() function and pass the original dictionary as the parameter.

Example : In this example the below code utilizes `json.dumps()` to pretty-print the dictionary `test_dict` with an indentation of 4 spaces. The formatted string is then printed for improved readability.




import json
 
# using json.dumps() to Pretty Print
pretty_dict = json.dumps(test_dict, indent=4)
print("The Pretty Print dictionary is : \n", pretty_dict)

Output:

The original dictionary is :  {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
The Pretty Print dictionary is : 
 {
    "gfg": {
        "rate": 5,
        "remark": "good"
    },
    "cs": {
        "rate": 3
    }
}

Time Complexity: O(n)
Auxiliary Space: O(1)


Article Tags :