我正在尝试打印一本漂亮的字典,但我没有运气:
>>> 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。
使用
width=1
或 width=-1
:
In [33]: pprint.pprint(a, width=1)
{'first': 123,
'second': 456,
'third': {1: 1,
2: 2}}
您可以通过
json.dumps(d, indent=4)
将 dict 转换为 json
import json
print(json.dumps(item, indent=4))
{
"second": 456,
"third": {
"1": 1,
"2": 2
},
"first": 123
}
如果您想漂亮地打印环境变量,请使用:
pprint.pprint(dict(os.environ), width=1)
在 Ryan Chou 已经非常有用的答案之上添加两件事:
sort_keys
参数,以便更轻松地理解你的字典,尤其是。如果您使用的是 3.6 之前的 Python(其中字典是无序的)print(json.dumps(item, indent=4, sort_keys=True))
"""
{
"first": 123,
"second": 456,
"third": {
"1": 1,
"2": 2
}
}
"""
dumps()
仅当字典键是基元(字符串、int 等)时才有效作为
pprint
的替代方案,从 Python 3.12 开始,您可以使用内置的 reprlib
模块进行漂亮打印:
>>> from reprlib import Repr
>>> example = {'first': 123, 'second': 456, 'third': {1: 1, 2: 2}}
>>> print(Repr(indent=4).repr(example))
{
'first': 123,
'second': 456,
'third': {
1: 1,
2: 2,
},
}
>>>
您可以使用
maxlevel
关键字参数来决定嵌套字典应打印的深度:
>>> print(Repr(indent=4, maxlevel=1).repr(example))
{
'first': 123,
'second': 456,
'third': {...},
}
>>>
这是一个用于测试目的的复制面食并帮助提供使用示例。
from pprint import pprint # I usually only need this module from the package.
a = {'first': 123, 'second': 456, 'third': {1:1, 2:2}, 'zfourth': [{3:9, 7:8}, 'distribution'], 1:2344, 2:359832, 3:49738428, 4:'fourth', 5:{'dictionary':'of things', 'new':['l','i','s','t']}}
pprint(dict(a), indent=4, width=1)
# Wrap your variable in dict() function
# Optional: indent=4. for readability
# Required: width=1 for wrapping each item to its own row.
# Note: Default pprint is to sort the dictionary
# Note: This also auto-wraps anything sting that has spaces in it. See 'of things' below.
# Documentation: https://docs.python.org/3/library/pprint.html
# Examples: https://pymotw.com/2/pprint/
# Blog: https://realpython.com/python-pretty-print/
提供以下结果:
{ 1: 2344,
2: 359832,
3: 49738428,
4: 'fourth',
5: { 'dictionary': 'of '
'things',
'new': [ 'l',
'i',
's',
't']},
'first': 123,
'second': 456,
'third': { 1: 1,
2: 2},
'zfourth': [ { 3: 9,
7: 8},
'distribution']}