下面是通过覆盖和使用内部股票pprint()
功能中的另一种答案。不像我的earlier one它将处理OrderedDict
的另一个容器,如list
的内部,并且还应该能够处理给定的任何可选关键字参数 - 但它没有控制另一个输出提供的输出相同程度的控制。
它通过将库存函数的输出重定向到一个临时缓冲区进行操作,然后在将它发送到输出流之前将其换行。虽然最终产出并不是特别漂亮,但它很体面,可能“足够好”可以用作解决方法。
更新2.0
通过使用标准库textwrap
模块简化,并且修改 Python 2中& 3两者工作。
from collections import OrderedDict
try:
from cStringIO import StringIO
except ImportError: # Python 3
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: # unlimited, use stock function
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()
# word wrap output onto multiple lines <= width characters
try:
print >> stream, textwrap.fill(' '.join(words), width=width)
except TypeError: # Python 3
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)
» {'john': 1, 'mary': 3, 'paul': 2}
pprint(od, width=40)
» OrderedDict([('john', 1), ('paul', 2),
('mary', 3)])
pprint(lod, width=40)
» [OrderedDict([('john', 1), ('paul', 2),
('mary', 3)]), OrderedDict([('moe', 1),
('curly', 2), ('larry', 3)]),
OrderedDict([('weapons', 1), ('mass',
2), ('destruction', 3)])]
可能要考虑打开一个bug。 – 2010-11-29 05:29:59
我正在考虑这样做。我会在这里发布更新,如果我这样做。 – 2010-11-29 05:36:13
建议添加有关有序字典的评论到http://bugs.python.org/issue7434 – 2010-11-29 08:51:32