gmxnqg
Last Updated: June 24, 2019
·
84.57K
· hartleybrody

Pretty Printing a Python dictionary

I just discovered this one yesterday. If you have a dictionary with more than a few items you need to be able to read, the json.dumps() function takes an indent argument that automatically formats things legibly for you:

import json
...
print json.dumps(my_dict, indent=1)

You can even add sort_keys=True to... you guessed it! Sort the output alphabetically by keys. More info.

7 Responses
Add your response

1455

Alternatively. You can do this:

import pprint

pprint.pprint(whateverdatastructureyouwant)

over 1 year ago ·
1487

Beware, I think this will only work with simple data types. If you have a date, object, etc you'll get an error. I imagine @wyuenho's method will work around that.

over 1 year ago ·
29862

Nice.. and I would love to suggest a tool for json pretty print, https://jsonformatter.org/json-pretty-print

over 1 year ago ·
31248

Very useful information for people!

8 months ago ·
31457

I have a same opinion with Jason Sanford.

7 months ago ·
32005

Thanks for sharing this great. Keep sharing more useful and conspicuous stuff like this. Thank you so much
https://chinesewuxia.world

5 months ago ·
34106

Nice article thanks for sharing…… https://www.kodi.link/

22 days ago ·