Wednesday 7 February 2024

Pretty print dictionary content in Python

Approach 1: Writing custom function.

pretty_print_dictionary.py

def pretty_print_dict(dict, indent=0):
    for key, value in dict.items():
        if isinstance(value, dict):
            print(' ' * indent + str(key) + ':')
            pretty_print_dict(value, indent + 4)
        else:
            print(' ' * indent + str(key) + ': ' + str(value))

# Example usage:
address = {'city' : 'Banaglore', 'state' : 'Karnataka', 'country' : 'India'}
employee = {'name' : 'Krishna', 'age' : 34, 'address' : address}

pretty_print_dict(employee)

Output

name: Krishna
age: 34
address:
    city: Banaglore
    state: Karnataka
    country: India

In the above snippet, pretty_print_dict function takes a dictionary ‘dict’ as input and prints it in a human-readable format, with nested dictionaries indented by 4 spaces. You can adjust the indentation by modifying the indent parameter.

 

Approach 2: Using pprint module.

Using ‘pprint’ module, we can print the dictionary content in pretty formant Python.

 

pretty_print_dict.py

import pprint

address = {'city' : 'Bangalore', 'state' : 'Karnataka', 'country' : 'India'}
employee = {'name' : 'Krishna', 'age' : 34, 'address' : address}

pprint.pprint(employee)

Output

{'address': {'city': 'Bangalore', 'country': 'India', 'state': 'Karnataka'},
 'age': 34,
 'name': 'Krishna'}

This Python snippet demonstrates the use of the pprint module to pretty-print a nested Python dictionary.

 

import pprint

This line imports the pprint module, which contains the pprint() function. This function is used to print Python data structures in a way that's more readable than the standard print function.

 

pprint.pprint(employee)

This line calls the pprint() function from the pprint module to print the employee dictionary. The pprint function formats the output in a more readable way, especially useful for nested or complex data structures.

 

Approach 3: Using json module.

You can use the json module in Python to pretty print dictionary content. Here's a simple example:

 

pretty_print_dict_by_json_module.py

import json
def pretty_print_dict(dict, indent=0):
   return json.dumps(dict, indent=4)

# Example usage:
address = {'city' : 'Banaglore', 'state' : 'Karnataka', 'country' : 'India'}
employee = {'name' : 'Krishna', 'age' : 34, 'address' : address}

print(pretty_print_dict(employee))

Output

{
    "name": "Krishna",
    "age": 34,
    "address": {
        "city": "Banaglore",
        "state": "Karnataka",
        "country": "India"
    }
}

The indent parameter in json.dumps() is used to specify the indentation level for the output, making it easier to read.


Previous                                                 Next                                                 Home

No comments:

Post a Comment