The Wayback Machine - https://web.archive.org/web/20240717024538/https://www.geeksforgeeks.org/python-pretty-print-a-dictionary-with-dictionary-value/
Open In App

Python | Pretty Print a dictionary with dictionary value

Last Updated : 11 Dec, 2023
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

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

Pretty Print JSON in Python
JSON is a javascript notation of storing and fetching the data. Data is usually stored in JSON, XML or in some other database. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called json. Note: For more information, refer to Read, Write and Parse JSON using Python Pretty Print JSON Whenever d
2 min read
Pretty print Linked List in Python
Creating custom data types can be tricky, especially when you want to use it like any other data type. Linked List can be thought of as an example of a custom data type. In other languages, if you want to print the linked list, you would define a separate print function, something like pprint but it looks kind of odd, right? Like it would be great
3 min read
Python - Pretty Print JSON
JSON stands for JavaScript Object Notation. It is a format for structuring data. This format is used by different web applications to communicate with each other. In this article, we will learn about JSON pretty print What is JSON?JSON (JavaScript Object Notation) is a text-based data format that is interchangeable with many programming languages.
5 min read
How to Pretty Print an Entire Pandas Series or DataFrame?
In this article, we are going to see how to Pretty Print the entire pandas Series / Dataframe. There are various pretty print options are available for use with this method. Here we will discuss 3 ways to Pretty Print the entire Pandas Dataframe: Use pd.set_options() methodUse pd.option_context() methodUse options.display() MethodCreating DataFrame
3 min read
Pretty Printing XML in Python
XML stands for Extensible Markup Language and is used to encode a document that can be understandable by both humans and machines. Data stored in XML format is easy to understand and easy to modify. There are three main things that have to keep in mind when you are using XML – Simplicity, Generality, and Usability. Pretty Printing XML using xml.dom
2 min read
pprint : Data pretty printer in Python
This article is about a pretty useful built-in module in Python, pprint. The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a well-formatted and more readable way! Let us consider an example: # A python code without pprint import requests def geocode(address): url = "https://maps.googleapis.com/maps/a
2 min read
Pretty-Printing in BeautifulSoup
Prerequisite: requestsBeautifulSoup In this article, we will learn about how to print pretty in BeautifulSoup Using Python. The requests library is an integral part of Python for making HTTP requests to a specified URL. Whether it be REST APIs or Web Scraping, requests are must be learned for proceeding further with these technologies. When one mak
2 min read
Print anagrams together in Python using List and Dictionary
Given an array of words, print all anagrams together. Examples: Input: arr = ['cat', 'dog', 'tac', 'god', 'act'] Output: 'cat tac act dog god' This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Appr
2 min read
Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45} Output: 12, 10, 9, 45, 2 Input: arr[] = {1, 2, 3, 4, 5} Output: 1, 2, 3, 4, 5 Input: arr[] = {1, 1, 1, 1, 1}
2 min read
Python program to print the dictionary in table format
Given a Dictionary. The task is to print the dictionary in table format. Examples: Input: {1: ["Samuel", 21, 'Data Structures'], 2: ["Richie", 20, 'Machine Learning'], 3: ["Lauren", 21, 'OOPS with java'], }Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS with java Method 1: Displaying results by iterating
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg