Python | Pretty Print a dictionary with dictionary value

Python | Pretty Print a dictionary with dictionary value

Pretty printing a dictionary in Python, especially when the dictionary contains nested dictionaries, can enhance readability. The pprint module in Python's standard library provides this functionality.

Objective:

To pretty-print a dictionary, which contains other dictionaries as values.

Example:

Consider the dictionary:

data = { 'Alice': { 'age': 28, 'occupation': 'Engineer', 'location': 'New York' }, 'Bob': { 'age': 34, 'occupation': 'Data Scientist', 'location': 'San Francisco' } } 

Steps and Python Code:

1. Using pprint.pprint():

The pprint module contains a function pprint() that automatically formats and prints complex Python data structures in a format that's easier to read than the standard print() function.

import pprint data = { 'Alice': { 'age': 28, 'occupation': 'Engineer', 'location': 'New York' }, 'Bob': { 'age': 34, 'occupation': 'Data Scientist', 'location': 'San Francisco' } } pprint.pprint(data, width=40, indent=4) 

2. Using pprint.PrettyPrinter():

If you want more control over the printing process or want to reuse the same printing configuration multiple times, you can create an instance of the PrettyPrinter class.

import pprint data = { 'Alice': { 'age': 28, 'occupation': 'Engineer', 'location': 'New York' }, 'Bob': { 'age': 34, 'occupation': 'Data Scientist', 'location': 'San Francisco' } } printer = pprint.PrettyPrinter(width=40, indent=4) printer.pprint(data) 

Explanation:

  • The width parameter in both methods specifies the desired maximum width of the output. If the output has nested structures, pprint will try to fit them within this width.

  • The indent parameter specifies the number of spaces to add for each level of nesting.

Considerations:

  • Adjust the width and indent parameters to better fit your specific use case or output format.

  • For dictionaries with deep nesting, pretty printing can significantly improve readability. However, for large datasets, be mindful of output length.

By following this tutorial, you've learned how to pretty-print dictionaries, including those with nested dictionaries, using Python's pprint module.


More Tags

python-3.3 load-testing colorama mplcursors primeng-datatable progress-indicator subplot mpvolumeview linked-list aspect-ratio

More Programming Guides

Other Guides

More Programming Examples