pprint dictionary on multiple lines

自闭症网瘾萝莉.ら 提交于 2019-12-28 11:42:33

问题


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 pprint do this? If not, then which module does it? I'm using Python 2.7.3.


回答1:


Use width=1 or width=-1:

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



回答2:


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

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



回答3:


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

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



回答4:


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

  • pass the sort_keys argument for an easier visual grok on your dict, esp. if you're working with pre-3.6 Python (in which dictionaries are unordered)
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.)


来源:https://stackoverflow.com/questions/20171392/pprint-dictionary-on-multiple-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!