How to Pretty Print Dictionary in Python

I have spent countless hours staring at messy, unreadable terminal outputs. When you are fetching data from a US Census Bureau API or a complex financial database on Wall Street, a standard print() statement usually returns a wall of text.

It is frustrating to debug a nested dictionary that looks like a single, never-ending line of code.

Over the years, I have learned that “pretty printing” isn’t just about making things look nice; it is about saving time and reducing errors.

In this guide, I will show you exactly how I format Python dictionaries so they are easy to read and analyze.

Why Standard Printing Fails for Large Data

When I first started building data pipelines for logistics companies in Chicago, I relied on the built-in print() function.

For small dictionaries, it works fine. But as soon as you handle nested structures, like a list of employee records in a California tech firm, the output becomes a disaster.

Standard printing doesn’t provide indentation or line breaks, making it nearly impossible to spot missing keys or incorrect values.

Method 1: Use the Built-in pprint Module

The pprint (Data Pretty Printer) module is the first tool I reach for when I need a quick look at my data.

It is part of the Python Standard Library, so you don’t need to install anything extra.

I find it particularly useful when I want to control the indentation and the width of the output.

The Code Example: Map US Office Locations

import pprint

# A complex dictionary representing corporate offices across the USA
us_corp_structure = {
    "Headquarters": {
        "Location": "New York City, NY",
        "Departments": ["Finance", "Legal", "Operations"],
        "Staff_Count": 1250
    },
    "Regional_Hubs": [
        {
            "City": "Austin, TX",
            "Focus": "Technology and Innovation",
            "Teams": ["Cloud Architecture", "Data Science", "Backend"]
        },
        {
            "City": "Seattle, WA",
            "Focus": "Cloud Logistics",
            "Teams": ["AWS Integration", "Supply Chain AI"]
        }
    ],
    "Remote_Work_Policy": True,
    "Tax_ID": "99-1234567"
}

# Creating a PrettyPrinter object with specific indentation
pp = pprint.PrettyPrinter(indent=4, width=50)

print("Standard Print Output:")
print(us_corp_structure)

print("\n--- Pretty Print Output ---")
pp.pprint(us_corp_structure)

I executed the above example code and added the screenshot below.

Pretty Print Dictionary Python

When I use pprint, I usually set the width parameter.

If the width is too small, the module will force nested items onto new lines, which is exactly what you want for readability.

It’s my go-to for quick debugging sessions in the terminal.

Method 2: Use the json.dumps() Method

While pprint is great for Python objects, I often prefer json.dumps() when I am working with Web APIs or configuration files.

In my experience, json.dumps() produces the cleanest-looking output because it follows the strict JSON format.

I used this method extensively while developing a real estate listing aggregator for the Florida market.

The Code Example: Real Estate Data Formatting

import json

# Dictionary representing a luxury real estate listing in Los Angeles
listing_data = {
    "property_id": "LA-90210-55",
    "address": "123 Sunset Blvd, Beverly Hills, CA",
    "specs": {
        "bedrooms": 5,
        "bathrooms": 6,
        "sq_ft": 5200,
        "lot_size_acres": 0.75
    },
    "amenities": ["Infinity Pool", "Home Theater", "Wine Cellar", "Smart Home System"],
    "listing_agent": {
        "name": "Sarah Jenkins",
        "agency": "West Coast Luxury Realty",
        "license_no": "CA-987654321"
    }
}

# Pretty printing using json.dumps
# indent=4 adds spacing, sort_keys organizes alphabetically
pretty_json = json.dumps(listing_data, indent=4, sort_keys=True)

print("Clean JSON-style Dictionary Print:")
print(pretty_json)

I executed the above example code and added the screenshot below.

Pretty Print Python Dictionary

The sort_keys=True argument is a lifesaver. When comparing two dictionaries from different sources, having the keys in alphabetical order makes it much easier to spot differences.

Just remember that this only works if your dictionary keys are strings and the values are JSON-serializable.

Method 3: The “Rich” Library for Professional Terminals

If you want your terminal to look like a modern dashboard, I highly recommend the Rich library.

During a project for a federal agency in D.C., I had to present terminal outputs to stakeholders.

Using Rich allowed me to add colors and bold text to the dictionary output, making the data “pop.”

The Code Example: Visualize US Stock Market Data

# Note: You would need to run 'pip install rich' to use this
from rich import print as rprint

# Dictionary containing simulated stock performance for US Tech Giants
stock_portfolio = {
    "Portfolio_Owner": "Global Ventures LLC",
    "Currency": "USD",
    "Holdings": [
        {"Ticker": "AAPL", "Shares": 150, "Last_Price": 185.92, "Change": "+1.2%"},
        {"Ticker": "MSFT", "Shares": 80, "Last_Price": 405.32, "Change": "-0.5%"},
        {"Ticker": "GOOGL", "Shares": 120, "Last_Price": 142.71, "Change": "+0.8%"}
    ],
    "Last_Updated": "2024-05-20 14:30:00 EST"
}

print("Rich Library Pretty Print:")
rprint(stock_portfolio)

I executed the above example code and added the screenshot below.

How to Pretty Print Dictionary in Python

Rich handles indentation automatically and even color-codes different data types (strings vs. integers).

In my professional opinion, if you are building a Command Line Interface (CLI) for others to use, Rich is the gold standard.

Method 4: Custom Loops for Specific Formatting

Sometimes, none of the standard methods gives me exactly what I need.

When I was auditing healthcare data across different US states, I needed to format specific keys differently.

In these cases, I write a simple recursive function or a custom loop.

The Code Example: Format US Healthcare Statistics

# Dictionary of healthcare metrics by state
state_data = {
    "New York": {"Hospitals": 200, "Physicians": 45000, "Rating": "A"},
    "California": {"Hospitals": 350, "Physicians": 92000, "Rating": "A+"},
    "Texas": {"Hospitals": 310, "Physicians": 61000, "Rating": "B+"}
}

print("Custom Formatted Output:")
for state, metrics in state_data.items():
    print(f"State: {state}")
    for key, value in metrics.items():
        print(f"  -- {key}: {value}")
    print("-" * 20)

When to Use Custom Loops

I use this approach when the dictionary is too large to print in full, and I only want to see specific “highlights.”

It gives me total control over the visual hierarchy of the data.

Why is my dictionary not sorting?

If you use pprint, it sorts keys by default in Python 3.8+. If you use json.dumps, you must explicitly set sort_keys=True.

In this tutorial, I have shown you several ways to pretty print a Python dictionary based on my years of experience.

Whether you are a data scientist in San Francisco or a backend dev in New York, these tools will make your logs much easier to read.

I have found that taking the extra two seconds to implement a pretty print makes debugging a much smoother process.

Try these methods out in your next project and see which one fits your workflow best.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.