I have big dictionary which I`m printing for viewing with prettyprint, but how I can keep formatting but kill sorting mechanism in pprint?
Use sort_dicts=False
:
pprint.pprint(data, sort_dicts=False)
You can monkey patch the pprint module.
import pprint pprint.pprint({"def":2,"ghi":3,"abc":1,}) pprint._sorted = lambda x:x # Or, for Python 3.7: # pprint.sorted = lambda x, key=None: x pprint.pprint({"def":2,"ghi":3, "abc":1})
Since the 2nd output is essentiallly randomly sorted, your output may be different from mine:
{'abc': 1, 'def': 2, 'ghi': 3} {'abc': 1, 'ghi': 3, 'def': 2}
import pprint import contextlib @contextlib.contextmanager def pprint_nosort(): # Note: the pprint implementation changed somewhere # between 2.7.12 and 3.7.0. This is the danger of # monkeypatching! try: # Old pprint orig,pprint._sorted = pprint._sorted, lambda x:x except AttributeError: # New pprint import builtins orig,pprint.sorted = None, lambda x, key=None:x try: yield finally: if orig: pprint._sorted = orig else: del pprint.sorted # For times when you don't want sorted output with pprint_nosort(): pprint.pprint({"def":2,"ghi":3, "abc":1}) # For times when you do want sorted output pprint.pprint({"def":2,"ghi":3, "abc":1})
As of Python 3.8, you can finally disable this using sort_dicts=False
. Note that dictionaries are insertion-ordered since Python 3.7 (and in practice, even since 3.6).
import pprint data = {'not': 'sorted', 'awesome': 'dict', 'z': 3, 'y': 2, 'x': 1} pprint.pprint(data, sort_dicts=False) # prints {'not': 'sorted', 'awesome': 'dict', 'z': 3, 'y': 2, 'x': 1}
Alternatively, create a pretty printer object:
pp = pprint.PrettyPrinter(sort_dicts=False) pp.pprint(data)
This does not affect sets (which are still sorted), but then sets do not have insertion-ordering guarantees.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With