这里有另一个答案,通过覆盖并在内部使用原始的
pprint()
函数来实现。与我之前的
答案不同,它可以处理嵌套在其他容器(如
list
)中的
OrderedDict
,并且还应该能够处理给定的任何可选关键字参数 - 但它对输出的控制程度不如另一个方法。
它通过将原始函数的输出重定向到临时缓冲区,然后将其换行后发送到输出流。虽然最终产生的输出不是特别漂亮,但它还可以作为一种解决方法。
更新2.0
通过使用标准库的
textwrap
模块简化,并修改以在Python 2和3中运行。
from collections import OrderedDict
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
from pprint import pprint as pp_pprint
import sys
import textwrap
def pprint(object, **kwrds):
try:
width = kwrds['width']
except KeyError:
pp_pprint(object, **kwrds)
return
buffer = StringIO()
stream = kwrds.get('stream', sys.stdout)
kwrds.update({'stream': buffer})
pp_pprint(object, **kwrds)
words = buffer.getvalue().split()
buffer.close()
try:
print >> stream, textwrap.fill(' '.join(words), width=width)
except TypeError:
print(textwrap.fill(' '.join(words), width=width), file=stream)
d = dict((('john',1), ('paul',2), ('mary',3)))
od = OrderedDict((('john',1), ('paul',2), ('mary',3)))
lod = [OrderedDict((('john',1), ('paul',2), ('mary',3))),
OrderedDict((('moe',1), ('curly',2), ('larry',3))),
OrderedDict((('weapons',1), ('mass',2), ('destruction',3)))]
样例输出:
pprint(d, width=40)
» {'约翰': 1, '玛丽': 3, '保罗': 2}
pprint(od, width=40)
» 有序字典([('john', 1), ('paul', 2),
('mary', 3)])
pprint(lod, width=40)
» [有序字典([('john', 1), ('paul', 2),
('mary', 3)]), 有序字典([('moe', 1),
('curly', 2), ('larry', 3)]),
有序字典([('weapons', 1), ('mass',
2), ('destruction', 3)])]
pprint
将更好地处理OrderedDict
对象。 - Flimmdict
对象的(在Python的新版本中保留插入顺序),而不是关于OrderedDict
对象的。我修改了标题以使其更清晰。 - Flimmpprint
对dict
对象中的键进行排序,请参阅此问题:https://dev59.com/BF8e5IYBdhLWcg3wfajv - Flimm