Python | Pretty Print a dictionary with dictionary value
Last Updated :
11 Dec, 2023
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
# 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.
Python3
# 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.
Python3
# 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.
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) 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.
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
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.
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'}}
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.
Python3
# 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.
Python3
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)
Similar Reads
Python - Keys associated with value list in dictionary
Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in P
4 min read
Dictionary with Tuple as Key in Python
Dictionaries allow a wide range of key types, including tuples. Tuples, being immutable, are suitable for use as dictionary keys when storing compound data. For example, we may want to map coordinates (x, y) to a specific value or track unique combinations of values. Let's explores multiple ways to
4 min read
Python - Keys associated with Values in Dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to reform the dictionary, in the form in which all the values point to the keys that they belong to. This kind of problem can occur in many domains including web development and data domains. Lets discuss certain
5 min read
Get Key from Value in Dictionary - Python
The goal is to find the keys that correspond to a particular value. Since dictionaries quickly retrieve values based on keys, there isn't a direct way to look up a key from a value. Using next() with a Generator ExpressionThis is the most efficient when we only need the first matching key. This meth
5 min read
Write a dictionary to a file in Python
A dictionary store data using key-value pairs. Our task is that we need to save a dictionary to a file so that we can use it later, even after the program is closed. However, a dictionary cannot be directly written to a file. It must first be changed into a format that a file can store and read late
3 min read
Python - Concatenate Values with Same Keys in a List of Dictionaries
We are given a list of dictionaries where the values are lists and our task is to concatenate the values of the same keys across these dictionaries. For example, if we have a list of dictionaries like this: [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [
4 min read
How to Add Function in Python Dictionary
Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
4 min read
Bidirectional Hash table or Two way dictionary in Python
We know about Python dictionaries in a data structure in Python which holds data in the form of key: value pairs. In this article, we will discuss the Bidirectional Hash table or Two-way dictionary in Python. We can say a two-way dictionary can be represented as key ââ value. One example of two-way
3 min read
Return Dictionary from a Function in Python
Returning a dictionary from a function allows us to bundle multiple related data elements and pass them back easily. In this article, we will explore different ways to return dictionaries from functions in Python.The simplest approach to returning a dictionary from a function is to construct it dire
3 min read
Python Dictionary with For Loop
Combining dictionaries with for loops can be incredibly useful, allowing you to iterate over the keys, values, or both. In this article, we'll explore Python dictionaries and how to work with them using for loops in Python. Understanding Python DictionariesIn this example, a person is a dictionary w
2 min read