0 votes
1 view
in Python by (42.5k points)

How can I pretty-print a dictionary with a depth of ~4 in Python? I tried pretty printing with pprint(), but it did not work:

import pprint 

pp = pprint.PrettyPrinter(indent=4) 

pp.pprint(mydict)

I simply want an indentation ("\t") for each nesting, so that I get something like this:

key1 

value1 

value2 

key2 

Value1

value2

etc.

How can I do this?

1 Answer

0 votes
by (95.7k points)

You can use the below-mentioned code to pretty-print nested dictionary:-

def pretty(d, indent=0): 

for key, value in d.items():

print('\t' * indent + str(key))

if isinstance(value, dict):

pretty(value, indent+1)

else:

print('\t' * (indent+1) + str(value))

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...