多行打印字典

我试图找到一本漂亮的字典,但是没有找到:

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

我希望输出是多行的,如下所示:

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

pprint能做到这一点吗? 如果不能,那么哪个模块做到这一点? 我使用的是 Python 2.7.3

83552 次浏览

Use width=1 or width=-1:

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

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

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

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

import json


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

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.)