下面是通過覆蓋和使用內部股票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