python pprint dictionary on multiple lines

2019-01-22 16:57发布

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

3条回答
一夜七次
2楼-- · 2019-01-22 17:35

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楼-- · 2019-01-22 17:55

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

pprint.pprint(dict(os.environ), width=1)
查看更多
Bombasti
4楼-- · 2019-01-22 17:57

Use width=1 or width=-1:

In [33]: pprint.pprint(a, width=1)
{'first': 123,
 'second': 456,
 'third': {1: 1,
           2: 2}}
查看更多
登录 后发表回答