pprint dictionary on multiple lines

Learn pprint dictionary on multiple lines with practical examples, diagrams, and best practices. Covers python, python-2.7, dictionary development techniques with visual explanations.

Pretty Printing Python Dictionaries on Multiple Lines

Hero image for pprint dictionary on multiple lines

Learn how to use Python's pprint module to format dictionaries for enhanced readability, especially for complex or nested data structures.

When working with Python dictionaries, especially those with many keys, long values, or nested structures, the default print() function can output a single, hard-to-read line. The pprint module, short for 'pretty print', provides a way to format complex data structures, including dictionaries, into a more human-readable, multi-line format. This article will guide you through using pprint effectively to improve the readability of your Python dictionary outputs.

The Challenge of Default Dictionary Printing

By default, Python's print() function outputs dictionaries as a single line, which can quickly become unmanageable. This is particularly true for dictionaries containing many items, long string values, or nested dictionaries and lists. Debugging or simply understanding the structure of such an output can be a significant challenge.

my_dict = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York',
    'occupation': 'Software Engineer',
    'interests': ['programming', 'reading', 'hiking', 'cooking'],
    'contact': {
        'email': 'alice@example.com',
        'phone': '123-456-7890'
    }
}

print(my_dict)

Default output of a complex dictionary using print()

The output from the above code will be a single, long line, making it difficult to quickly grasp the dictionary's structure and content. This is where pprint comes in handy.

Introducing Python's pprint Module

The pprint module offers a pprint() function that formats the output of Python data structures, including dictionaries, lists, and tuples, in a way that is both visually appealing and easy to understand. It automatically handles indentation, line breaks, and alignment, making complex data structures much more digestible.

import pprint

my_dict = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York',
    'occupation': 'Software Engineer',
    'interests': ['programming', 'reading', 'hiking', 'cooking'],
    'contact': {
        'email': 'alice@example.com',
        'phone': '123-456-7890'
    }
}

pprint.pprint(my_dict)

Using pprint.pprint() for a multi-line dictionary output

Notice how pprint.pprint() automatically indents nested structures and places each key-value pair on a new line, significantly improving readability. You can also control the indentation and width of the output.

Customizing pprint Output

The pprint.pprint() function accepts several arguments to customize its output. The most commonly used are indent and width.

flowchart TD
    A[Start] --> B{Call pprint.pprint()}
    B --> C{Check 'indent' parameter}
    C -->|Yes| D[Use specified indentation]
    C -->|No| E[Use default indentation (1)]
    E --> F{Check 'width' parameter}
    D --> F
    F -->|Yes| G[Wrap lines at specified width]
    F -->|No| H[Use default width (80)]
    G --> I[Format dictionary for readability]
    H --> I
    I --> J[Output formatted dictionary]
    J --> K[End]

Flowchart illustrating pprint customization logic

  • indent: Specifies the number of spaces to indent each level. The default is 1.
  • width: Specifies the maximum desired width of the output. If a data structure cannot be formatted within this width, pprint will attempt to break lines to fit, but it might exceed the width if necessary to avoid breaking tokens.
  • depth: Specifies the number of levels to recurse. Deeper levels will be represented by ....
import pprint

my_dict = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York',
    'occupation': 'Software Engineer',
    'interests': ['programming', 'reading', 'hiking', 'cooking'],
    'contact': {
        'email': 'alice@example.com',
        'phone': '123-456-7890'
    }
}

print("\n--- Custom Indent (4 spaces) ---")
pprint.pprint(my_dict, indent=4)

print("\n--- Custom Width (40 characters) ---")
pprint.pprint(my_dict, width=40)

print("\n--- Limited Depth (1 level) ---")
pprint.pprint(my_dict, depth=1)

Customizing pprint output with indent, width, and depth

import pprint

my_dict = {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}}
formatted_string = pprint.pformat(my_dict, indent=2)
print("\n--- Using pformat() ---")
print(formatted_string)
print(type(formatted_string))

Using pprint.pformat() to get the formatted string