Pretty Print Nested Dictionaries in Python

How can I python pretty print dict with nested dictionaries in Python?

I have a dictionary with a depth of around 4, and I want to pretty print it with proper indentation. I tried using pprint() but it didn’t work as expected:

import pprint 
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)

I would like the output to have a tab indentation (\t) for each level of nesting, like this:

key1
    value1
    value2
    key2
        value1
        value2

How can I achieve this?

If you’re looking for a simple and effective way to format nested dictionaries, I recommend using json.dumps. It’s a straightforward way to achieve pretty-printed output:

import json
mydict = {
    'key1': ['value1', 'value2'],
    'key2': {'subkey1': 'subvalue1', 'subkey2': 'subvalue2'}
}
print(json.dumps(mydict, indent=4))

This will give you a clean and readable structure with consistent indentation. Although it won’t use tabs (\t) specifically, it works well for most purposes when using python pretty print dict.

Good suggestion above! If you need more control over the indentation style or don’t want to rely on json.dumps, here’s another way to handle it. pprint can still do the job with minimal setup:

import pprint
mydict = {
    'key1': ['value1', 'value2'],
    'key2': {'subkey1': 'subvalue1', 'subkey2': 'subvalue2'}
}
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)

This might not give you the exact tab-style output, but it’s quite handy for general-purpose use. If you’re still keen on tabs, you might consider writing a custom function like the recursive example shared below. Using python pretty print dict tools effectively often depends on your specific formatting needs.

I agree with the previous answers, but if you want ultimate control over the format—like tab-specific indentation—a custom recursive function is your best bet. Here’s an example:

def pretty_print(d, indent=0):
    for key, value in d.items():
        print('\t' * indent + str(key))
        if isinstance(value, dict):
            pretty_print(value, indent + 1)
        else:
            if isinstance(value, list):
                for item in value:
                    print('\t' * (indent + 1) + str(item))
            else:
                print('\t' * (indent + 1) + str(value))

mydict = {
    'key1': ['value1', 'value2'],
    'key2': {'subkey1': 'subvalue1', 'subkey2': 'subvalue2'}
}

pretty_print(mydict)

This custom function uses recursion to traverse through nested dictionaries. It even handles lists within the dictionary. With this approach, you can achieve precisely the tabbed output you’re looking for while effectively using python pretty print dict.