gmxnqg
Last Updated: August 19, 2017
·
28.73K
· hartleybrody
Dsc 0255

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.

Say Thanks
Respond

2 Responses
Add your response

1455
Img 0675

Alternatively. You can do this:

import pprint

pprint.pprint(whateverdatastructureyouwant)

over 1 year ago ·
1487
2461963bbb20e1a13779d6603b1cd929

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 ·