我喜欢Python中的pprint模块。我经常使用它进行测试和调试。我经常使用width选项来确保输出很好地符合我的终端窗口
直到他们在Python2.7中添加了新的ordered dictionary type(我非常喜欢的另一个很酷的特性)之前,它一直工作得很好。如果我试图漂亮地打印一个有序的字典,它不会很好地显示出来。与其将每个键值对放在自己的行上,不如将整个内容显示在一条长的行上,这条长的行包含了很多次,而且很难阅读:
>>> 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看到它
如果OrderedDict的顺序为alpha排序,则以下操作将起作用,因为pprint将在打印前对dict进行排序
自Python 3.7以来,Python保证字典中的键将保持其插入顺序。因此,如果您使用的是Python3.7+,则无需确保OrderedDict按字母顺序排序
自Python 3.7以来,Python保证字典中的键将保持其插入顺序。(尽管它们的行为与
OrderedDict
对象并不完全相同,因为两个dicta
和b
可以被视为相等a == b
,即使键的顺序不同,而OrderedDict
在测试相等性时会检查这一点。)Python 3.8或更新版本:
您可以使用
sort_dicts=False
来阻止它按字母顺序对它们进行排序:Python 3.7或更早版本:
作为临时解决方法,您可以尝试以JSON格式转储,而不是使用
pprint
您丢失了一些类型信息,但它看起来不错,并且保持了顺序
下面是另一个答案,它通过在内部重写和使用stock
pprint()
函数来工作。与我的earlier one不同,它将处理另一个容器(如list
)中的OrderedDict
,并且还应该能够处理给定的任何可选关键字参数-但是它对输出的控制程度与另一个容器不同它将stock函数的输出重定向到一个临时缓冲区,然后word在将其发送到输出流之前对其进行包装。虽然最终产出的产品也不例外地漂亮,但它很不错,可能“足够好”可以作为一种变通方法
更新2.0
通过使用标准库
textwrap
模块进行简化,并修改为在 Python2和;3.样本输出:
»
{'john': 1, 'mary': 3, 'paul': 2}
»
OrderedDict([('john', 1), ('paul', 2),
('mary', 3)])
»
[OrderedDict([('john', 1), ('paul', 2),
('mary', 3)]), OrderedDict([('moe', 1),
('curly', 2), ('larry', 3)]),
OrderedDict([('weapons', 1), ('mass',
2), ('destruction', 3)])]
相关问题 更多 >
编程相关推荐