我喜欢 Python 中的 pprint 模块。我经常用它来测试和调试。我经常使用 width 选项来确保输出在我的终端窗口中非常合适。
It has worked fine until they added the new 有序字典型式 in Python 2.7 (another cool feature I really like). If I try to pretty-print an ordered dictionary, it doesn't show nicely. Instead of having each key-value pair on its own line, the whole thing shows up on one long line, which wraps many times and is hard to read:
>>> from collections import OrderedDict
>>> o = OrderedDict([("aaaaa", 1), ("bbbbbb", 2), ("ccccccc", 3), ("dddddd", 4), ("eeeeee", 5), ("ffffff", 6), ("ggggggg", 7)])
>>> import pprint
>>> pprint.pprint(o)
OrderedDict([('aaaaa', 1), ('bbbbbb', 2), ('ccccccc', 3), ('dddddd', 4), ('eeeeee', 5), ('ffffff', 6), ('ggggggg', 7)])
这里有没有人有办法让它像旧的无序字典一样印得很好?如果我花足够的时间,我可能会想出一些办法,可能使用 PrettyPrinter.format 方法,但我想知道这里是否有人已经知道一个解决方案。
更新: 我为此提交了一份错误报告。你可以在 http://bugs.python.org/issue10592看到它。