How can I pretty print a dictionary with 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?
Here's something that will print any sort of nested dictionary, while keeping track of the "parent" dictionaries along the way.
This is a good starting point for printing according to different formats, like the one specified in OP. All you really need to do is operations around the Print blocks. Note that it looks to see if the value is 'OrderedDict()'. Depending on whether you're using something from Container datatypes Collections, you should make these sort of fail-safes so the elif block doesn't see it as an additional dictionary due to its name. As of now, an example dictionary like
will print
~altering code to fit the question's format~
Using the same example code, it will print the following:
This isn't exactly what is requested in OP. The difference is that a parent^n is still printed, instead of being absent and replaced with white-space. To get to OP's format, you'll need to do something like the following: iteratively compare dicList with the lastDict. You can do this by making a new dictionary and copying dicList's content to it, checking if i in the copied dictionary is the same as i in lastDict, and -- if it is -- writing whitespace to that i position using the string multiplier function.
I wrote this simple code to print the general structure of a json object in Python.
the result for the following data
is very compact and looks like this:
I took sth's answer and modified it slightly to fit my needs of a nested dictionaries and lists:
Which then gives me output like:
As others have posted, you can use recursion/dfs to print the nested dictionary data and call recursively if it is a dictionary; otherwise print the data.
Here's a function I wrote based on what sth's comment. It's works the same as json.dumps with indent, but I'm using tabs instead of space for indents. In Python 3.2+ you can specify indent to be a '\t' directly, but not in 2.7.
Ex:
Sth, i sink that's pretty ;)