Last modified: Jan 27, 2026 By Alexander Williams

Python Dict Pretty Print Guide & Examples

Python dictionaries are powerful data structures. They store key-value pairs. But large or nested dictionaries can be hard to read. The default print() function outputs them in a single line. This guide shows you how to pretty print them.

Pretty printing formats data for human readability. It adds indentation, line breaks, and sorting. This makes debugging and data inspection much easier.

The Problem with Default Printing

Look at this nested dictionary. The default print is messy.


# A complex nested dictionary
data = {
    "user": {
        "id": 12345,
        "name": "Alice",
        "contact": {"email": "[email protected]", "phone": "555-1234"},
        "preferences": ["python", "coding", "reading"]
    },
    "orders": [
        {"id": 1, "item": "laptop", "price": 999.99},
        {"id": 2, "item": "mouse", "price": 29.99}
    ],
    "metadata": {"version": "1.0", "active": True}
}
print(data)

{'user': {'id': 12345, 'name': 'Alice', 'contact': {'email': '[email protected]', 'phone': '555-1234'}, 'preferences': ['python', 'coding', 'reading']}, 'orders': [{'id': 1, 'item': 'laptop', 'price': 999.99}, {'id': 2, 'item': 'mouse', 'price': 29.99}], 'metadata': {'version': '1.0', 'active': True}}

This output is one long line. It's difficult to see the structure. You cannot easily find keys or values.

Using the pprint Module

Python's pprint module is the standard tool for pretty printing. It stands for "pretty print". Import it and use the pprint() function or PrettyPrinter class.


import pprint

# Use the pprint function
pprint.pprint(data)

{'metadata': {'active': True, 'version': '1.0'},
 'orders': [{'id': 1, 'item': 'laptop', 'price': 999.99},
            {'id': 2, 'item': 'mouse', 'price': 29.99}],
 'user': {'contact': {'email': '[email protected]', 'phone': '555-1234'},
          'id': 12345,
          'name': 'Alice',
          'preferences': ['python', 'coding', 'reading']}}

Notice the improved format. The dictionary is broken into lines. Nested elements are indented. Keys are sorted alphabetically by default.

Customizing pprint Output

The pprint() function accepts parameters for control.

Use indent to set the spaces for each level. Use width to define the maximum line length. Use depth to limit nesting levels. Use sort_dicts to turn key sorting on or off.


# Customize the output
pprint.pprint(data, indent=4, width=50, depth=2, sort_dicts=False)

{   'user': {   'id': 12345,
                'name': 'Alice',
                'contact': {...},
                'preferences': [...]},
    'orders': [   {'id': 1, 'item': 'laptop', 'price': 999.99},
                  {'id': 2, 'item': 'mouse', 'price': 29.99}],
    'metadata': {'version': '1.0', 'active': True}}

The depth=2 argument collapsed deeper levels into {...}. This is useful for getting a high-level view. For more control, create a PrettyPrinter object. This is helpful if you are printing many dictionaries. You can learn more about dictionary structure in our Python Dict Literal Guide & Examples.

Using json.dumps for Pretty Printing

The json module can also pretty print dictionaries. This is effective if your data is JSON-serializable. Use json.dumps() with the indent parameter.


import json

# Pretty print with JSON
pretty_json = json.dumps(data, indent=2)
print(pretty_json)

{
  "user": {
    "id": 12345,
    "name": "Alice",
    "contact": {
      "email": "[email protected]",
      "phone": "555-1234"
    },
    "preferences": [
      "python",
      "coding",
      "reading"
    ]
  },
  "orders": [
    {
      "id": 1,
      "item": "laptop",
      "price": 999.99
    },
    {
      "id": 2,
      "item": "mouse",
      "price": 29.99
    }
  ],
  "metadata": {
    "version": "1.0",
    "active": true
  }
}

The JSON output is very clean. It uses double quotes. It's perfect for APIs or configuration files. Remember, JSON cannot serialize all Python objects like sets or custom classes.

Custom Pretty Print Function

Sometimes you need a custom format. You can write your own function. This example prints each key-value pair on a new line with a custom prefix.


def custom_pretty_print(d, indent=0):
    """Recursively pretty print a dictionary."""
    for key, value in d.items():
        print('  ' * indent + str(key) + ':', end=' ')
        if isinstance(value, dict):
            print()  # New line for a nested dict
            custom_pretty_print(value, indent + 1)
        else:
            print(repr(value))  # Print the value on same line

# Test the custom function
custom_pretty_print(data)

user:
  id: 12345
  name: 'Alice'
  contact:
    email: '[email protected]'
    phone: '555-1234'
  preferences: ['python', 'coding', 'reading']
orders: [{'id': 1, 'item': 'laptop', 'price': 999.99}, {'id': 2, 'item': 'mouse', 'price': 29.99}]
metadata:
  version: '1.0'
  active: True

This function gives you full control. You can modify it to handle lists, tuples, and other types. It's a great learning exercise for understanding recursion and dictionary iteration. For more on accessing dictionary data, see Python Dictionary Keys: Guide & Examples.

When to Use Pretty Printing

Pretty printing is crucial for debugging. Use it when inspecting API responses. Use it for complex configuration data. Use it for logging state in your application.

It turns a data blob into a readable map. This saves time and reduces errors. It's also useful for generating reports or documentation from data.

Before you print, you might need to Check if Python Dictionary is Empty to avoid unnecessary output.

Conclusion

Pretty printing Python dictionaries is an essential skill. The pprint module is your go-to tool for general use. The json.dumps method is perfect for JSON data. Custom functions offer maximum flexibility.

Always format your data for readability. It makes development faster and more enjoyable. Start using these techniques in your next project. Your debugging sessions will become much easier.