Edd*_*Edd 7 python dictionary pretty-print pprint
我有正在打印的大词典,可以用prettyprint进行查看,但是如何保持格式但又不能杀死pprint中的排序机制?
Nor*_*ius 16
从 Python 3.8 开始,您终于可以禁用此. 请注意,从 Python 3.7 开始,字典是按插入顺序排列的(实际上,即使是从 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}
Run Code Online (Sandbox Code Playgroud)
或者,创建一个漂亮的打印机对象:
pp = pprint.PrettyPrinter(sort_dicts=False)
pp.pprint(data)
Run Code Online (Sandbox Code Playgroud)
这不会影响集合(仍然排序),但是集合没有插入顺序保证。
Rob*_*obᵩ 10
您可以猴子修补 pprint模块。
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})
Run Code Online (Sandbox Code Playgroud)
由于第二个输出基本上是随机排序的,因此您的输出可能与我的不同:
{'abc': 1, 'def': 2, 'ghi': 3}
{'abc': 1, 'ghi': 3, 'def': 2}
Run Code Online (Sandbox Code Playgroud)
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})
Run Code Online (Sandbox Code Playgroud)