I like the pprint module in Python. I use it a lot for testing and debugging. I frequently use the width option to make sure the output fits nicely within my terminal window.
It has worked fine until they added the new ordered dictionary type in Python 2.7 (another cool feature I really like). If I try to pretty-print an ordered dictionary, it doesn't show nicely. Instead of having each key-value pair on its own line, the whole thing shows up on one long line, which wraps many times and is hard to read.
Does anyone here have a way to make it print nicely, like the old unordered dictionaries? I could probably figure something out, possibly using the PrettyPrinter.format method, if I spend enough time, but I am wondering if anyone here already knows of a solution.
UPDATE: I filed a bug report for this. You can see it at http://bugs.python.org/issue10592.
You can also use this simplification of the kzh answer:
It preserves the order and will output almost the same than the webwurst answer (print through json dump).
The following will work if the order of your OrderedDict is an alpha sort, since pprint will sort a dict before print.
As a temporary workaround you can try dumping in JSON format. You lose some type information, but it looks nice and keeps the order.
As of Python 3.8 :
pprint.PrettyPrinter
exposes thesort_dicts
keyword parameter.True by default, setting it to False will leave the dictionary unsorted.
Will output :
Reference : https://docs.python.org/3/library/pprint.html
Here’s a way that hacks the implementation of
pprint
.pprint
sorts the keys before printing, so to preserve order, we just have to make the keys sort in the way we want.Note that this impacts the
items()
function. So you might want to preserve and restore the overridden functions after doing the pprint.The
pprint()
method is just invoking the__repr__()
method of things in it, andOrderedDict
doesn't appear to do much in it's method (or doesn't have one or something).Here's a cheap solution that should work IF YOU DON'T CARE ABOUT THE ORDER BEING VISIBLE IN THE PPRINT OUTPUT, which may be a big if:
I'm actually surprised that the order isn't preserved... ah well.