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?
I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:
(for python 2 user: import the print function from __future__)
My first thought was that the JSON serializer is probably pretty good at nested dictionaries, so I'd cheat and use that:
I'm a relative python newbie myself but I've been working with nested dictionaries for the past couple weeks and this is what I had came up with.
You should try using a stack. Make the keys from the root dictionary into a list of a list:
Going in reverse order from last to first, lookup each key in the dictionary to see if its value is (also) a dictionary. If not, print the key then delete it. However if the value for the key is a dictionary, print the key then append the keys for that value to the end of the stack, and start processing that list in the same way, repeating recursively for each new list of keys.
If the value for the second key in each list were a dictionary you would have something like this after several rounds:
The upside to this approach is that the indent is just
\t
times the length of the stack:The downside is that in order to check each key you need to hash through to the relevant sub-dictionary, though this can be handled easily with a list comprehension and a simple
for
loop:Be aware that this approach will require you to cleanup trailing empty lists, and to delete the last key in any list followed by an empty list (which of course may create another empty list, and so on).
There are other ways to implement this approach but hopefully this gives you a basic idea of how to do it.
EDIT: If you don't want to go through all that, the
pprint
module prints nested dictionaries in a nice format.