This article provides a quick way to pretty print a dictionary that has 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.
Example
Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}}
Output: gfg:
remark: good
rate: 5
cs:
rate: 3
Pretty Print a Dictionary with Dictionary Value
Let us see a few ways we can pretty print a dictionary in Python whose values are also a dictionary.
- Using Nested For Loops
- Using the built-in JSON Module
- Using Recursion
- Using For Loop
- Using pprint Module
Using Nested For Loops
In this approach, we just nested for loop through each dictionary element and its corresponding values using a brute manner.
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': {'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)
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.
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)
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.
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
Time Complexity: O(N), where N is the total number of elements in the dictionary since it iterates through each element once.
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.
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.
Python3
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
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) |
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.