Disabling sorting mechanism in pprint output
Python 3.8 or newer:
Use sort_dicts=False
:
pprint.pprint(data, sort_dicts=False)
Python 3.7 or older:
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}
Another version that is more complex, but easier to use:
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.