I have big dictionary which I`m printing for viewing with prettyprint, but how I can keep formatting but kill sorting mechanism in pprint?
Advertisement
Answer
Python 3.8 or newer:
Use sort_dicts=False
:
JavaScript
x
2
1
pprint.pprint(data, sort_dicts=False)
2
Python 3.7 or older:
You can monkey patch the pprint module.
JavaScript
1
8
1
import pprint
2
3
pprint.pprint({"def":2,"ghi":3,"abc":1,})
4
pprint._sorted = lambda x:x
5
# Or, for Python 3.7:
6
# pprint.sorted = lambda x, key=None: x
7
pprint.pprint({"def":2,"ghi":3, "abc":1})
8
Since the 2nd output is essentiallly randomly sorted, your output may be different from mine:
JavaScript
1
3
1
{'abc': 1, 'def': 2, 'ghi': 3}
2
{'abc': 1, 'ghi': 3, 'def': 2}
3
Another version that is more complex, but easier to use:
JavaScript
1
31
31
1
import pprint
2
import contextlib
3
4
@contextlib.contextmanager
5
def pprint_nosort():
6
# Note: the pprint implementation changed somewhere
7
# between 2.7.12 and 3.7.0. This is the danger of
8
# monkeypatching!
9
try:
10
# Old pprint
11
orig,pprint._sorted = pprint._sorted, lambda x:x
12
except AttributeError:
13
# New pprint
14
import builtins
15
orig,pprint.sorted = None, lambda x, key=None:x
16
17
try:
18
yield
19
finally:
20
if orig:
21
pprint._sorted = orig
22
else:
23
del pprint.sorted
24
25
# For times when you don't want sorted output
26
with pprint_nosort():
27
pprint.pprint({"def":2,"ghi":3, "abc":1})
28
29
# For times when you do want sorted output
30
pprint.pprint({"def":2,"ghi":3, "abc":1})
31