Python 多行 pprint 字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20171392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:45:43  来源:igfitidea点击:

pprint dictionary on multiple lines

pythonpython-2.7dictionarypprint

提问by mulllhausen

I'm trying to get a pretty print of a dictionary, but I'm having no luck:

我正在尝试打印一本漂亮的字典,但我没有运气:

>>> import pprint
>>> a = {'first': 123, 'second': 456, 'third': {1:1, 2:2}}
>>> pprint.pprint(a)
{'first': 123, 'second': 456, 'third': {1: 1, 2: 2}}

I wanted the output to be on multiple lines, something like this:

我希望输出在多行上,如下所示:

{'first': 123,
 'second': 456,
 'third': {1: 1,
           2: 2}
}

Can pprintdo this? If not, then which module does it? I'm using Python 2.7.3.

可以pprint这样做吗?如果不是,那么是哪个模块呢?我正在使用Python 2.7.3

采纳答案by Warren Weckesser

Use width=1or width=-1:

使用width=1width=-1

In [33]: pprint.pprint(a, width=1)
{'first': 123,
 'second': 456,
 'third': {1: 1,
           2: 2}}

回答by UngodlySpoon

If you are trying to pretty print the environment variables, use:

如果您想漂亮地打印环境变量,请使用:

pprint.pprint(dict(os.environ), width=1)

回答by Ryan Chou

You could convert the dict to json through json.dumps(d, indent=4)

您可以通过将 dict 转换为 json json.dumps(d, indent=4)

print(json.dumps(item, indent=4))
{
    "second": 456,
    "third": {
        "1": 1,
        "2": 2
    },
    "first": 123
}

回答by Zach Valenta

Two things to add on top of Ryan Chou's already very helpful answer:

除了 Ryan Chou 已经非常有用的答案之外,还有两件事要添加:

  • pass the sort_keysargument for an easier visual grok on your dict, esp. if you're working with pre-3.6 Python (in which dictionaries are unordered)
  • sort_keys在你的 dict 上传递一个更容易视觉grok的参数,尤其是。如果您使用的是 3.6 之前的 Python(其中字典是无序的)
print(json.dumps(item, indent=4, sort_keys=True))
"""
{
    "first": 123,
    "second": 456,
    "third": {
        "1": 1,
        "2": 2
    }
}
"""
  • dumps()will only work if the dictionary keys are primitives (strings, int, etc.)
  • dumps()仅当字典键是基元(字符串、整数等)时才有效