The Wayback Machine - https://web.archive.org/web/20230512160721/https://www.geeksforgeeks.org/python-pretty-print-a-dictionary-with-dictionary-value/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Python | Pretty Print a dictionary with dictionary value

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

Method 1: Using loops We just loop through each dictionary element and its corresponding values using brute manner of loops. 

Step-by-step approach :

  • Create a dictionary with nested dictionaries as values.
  • Print the original dictionary.
  • Loop through the top-level keys of the dictionary.
    • For each top-level key, print it.
  • Loop through the keys of the nested dictionary associated with the top-level key.
    • For each key in the nested dictionary, print the key-value pair in the format “key: value”.

Below is the implementation of the above approach:

Python3




# 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))
 
# 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': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}
The Pretty Print dictionary is : 
gfg
remark : good
rate : 5
cs
rate : 3

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

Method 2: Using the built-in json module

STEPS: 

  1. First, the program imports the json module to use its dumps() function for pretty printing dictionaries.
  2. The program initializes a nested dictionary called test_dict with two keys: gfg and cs.
  3. The gfg key has two nested key-value pairs, rate and remark, with values of 5 and ‘good’, respectively.
  4. The cs key has only one nested key-value pair, rate, with a value of 3.
  5. The program prints the original dictionary using the print() function and the test_dict variable.
  6. The program uses the dumps() function from the json module to pretty print the test_dict dictionary.
  7. The pretty printed dictionary is assigned to a new variable called pretty_dict.
  8. Finally, the program prints the pretty printed dictionary using the print() function and the pretty_dict variable. The indent argument is set to 4 to make the output more readable.

Python3




import json
 
# initializing dictionary
test_dict = {'gfg': {'rate': 5, 'remark': 'good'}, 'cs': {'rate': 3}}
 
# printing original dictionary
print("The original dictionary is : ", test_dict)
 
# 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)

Method 3:Using recursion and string concatenation: 

1. The function starts by initializing an empty string, res.
2. Then it loops over each item in the input dictionary d by calling the items method. This operation takes O(N) time where N is the number of items in the dictionary.
3. Inside the loop, the function appends a string to res using the += operator. The length of the string being appended is proportional to the 4.current value of indent and the length of the key and value being printed. Assuming the maximum length of key and value to be M, the time 5.complexity of each iteration of the loop is O(indent + M).
6.If the current value is a dictionary, the function calls itself recursively with the inner dictionary and an incremented value of indent. The recursive 7.call will have to traverse through all the items in the nested dictionary. Therefore, the time complexity of the recursive call is O(M*k) where k is the number of items in the nested dictionary.
8.Finally, the function returns the resulting string res.

Python3




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

The time complexity: O(N), where N is the total number of elements in the dictionary, since it iterates through each element once.

The auxiliary space: O(N), since it stores the output string in memory, and the size of the output string is proportional to the size of the dictionary. Additionally, the recursive calls to pretty_print_dict also use stack space, which could potentially grow to O(N) in the worst case scenario where the dictionary is deeply nested.

Method 4: Using for loop+dictionary

Approach

for loop to iterate over the keys and values of the dictionary.

Algorithm

  •  Initialize an empty string to hold the pretty-printed dictionary.
  •  Iterate over the keys and values of the dictionary using a for loop.
  •  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.
  •  Return the pretty-printed dictionary string.

Python3




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

Output

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

Method 5: 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.

Python3




# 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'}}

The time complexity of the pprint module function pprint() depends on the size of the input dictionary.

The space complexity of the pprint module function pprint() is also dependent on the size of the input dictionary.

Method 6: using the json.dumps() method with an argument indent. 

Step-by-step approach:

  • Import the json module.
  • Initialize the dictionary.
  • Print the original dictionary.
  • Use json.dumps() method with indent argument to pretty print the dictionary.
  • Print the pretty printed dictionary.

Below is the implementation of the above approach:

Python3




# Importing json module
import json
 
# Initializing dictionary
test_dict = {'gfg' : {'rate' : 5, 'remark' : 'good'}, 'cs' : {'rate' : 3}}
 
# Printing original dictionary
print("The original dictionary is : ", test_dict)
 
# Using json.dumps() with indent argument to Pretty Print
print("The Pretty Print dictionary is : ")
pretty_print_dict = json.dumps(test_dict, indent=4)
print(pretty_print_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), 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.


My Personal Notes arrow_drop_up
Last Updated : 05 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials