python - 使用 pprint 强制垂直显示

标签 python dictionary pretty-print

我正在使用 pprint 来显示两个词典之间的 diff。有时字典中的值是长字符串,我希望将其视为单行,因此我将 width 设置为某个较大的值。不幸的是,有时这些字典很浅(即,虽然在一般情况下它们可以嵌入列表和字典,但有些只是具有短字符串值的字典)在这种情况下 pprint 将它们“漂亮地打印”在单行:

>>> pprint.pprint({'a': 'a', 'b': 'b'})
{'a': 'a', 'b': 'b'}

有没有办法强制 pprint 始终垂直显示列表和字典?同样,width 不是一个选项,因为它在行内拆分字符串(即,在 \n 上打断是好的,但在其他地方则不然)。

>>> pprint.pprint({'a': 'a ' * 50}, width=20)
{'a': 'a a a a a a '
      'a a a a a a '
      'a a a a a a '
      'a a a a a a '
      'a a a a a a '
      'a a a a a a '
      'a a a a a a '
      'a a a a a a '
      'a a '}

如果 pprint 不合适,是否有一些标准库可以让我免于编写专用例程?

最佳答案

选项:使用json

我发现将字典转换为 JSON 比 pprint 更可预测。在 此外,您可以选择对键进行排序,这应该有助于您 对比

    >>> import json

    >>> d1 = {'a': 'a', 'b': 'b', 'c':'c'}
    >>> print(json.dumps(d1, sort_keys=True, indent=''))
    {
    "a": "a",
    "b": "b",
    "c": "c"
    }
    >>> d2 = {'a': 'a ' * 50, 'b':'b', 'c': 'c ' * 50}
    >>> print(json.dumps(d2, sort_keys=True, indent=''))
    {
    "a": "a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a ",
    "b": "b",
    "c": "c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c "
    }

关于python - 使用 pprint 强制垂直显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555387/

相关文章:

python - 内存转储格式为 gdb 中的 xxd

python - pyserial 中的 inter_byte_timeout (interCharTimeout) 是什么?

python - 如果转换为序列或映射,则要进行不同转换的类

c++ - 我如何漂亮地打印一个结构,其字段被命名?

java - Hazelcast内部共享f分布式 map

wpf - 来自静态资源的WPF窗口标题

python - 在 Python 中漂亮地打印 XML

python - 在 Python Tools for Visual Studio 中调试 GAE

python - 并行运行多个子进程 - python 2.7

python - 在同一行从列表中切片和删除