最新消息:

Python 字典 格式化输出,树形输出

python admin 9744浏览 0评论

jsondumps

Python 默认输出字典是一行,查找和查看都不方便,如下

[root@aikaiyuan control_sh]# cat t.py
a = {'temperature_status': 'OP_STATUS_OK', 'cpu_status': 'OP_STATUS_OK', 'system_health': 'OP_STATUS_OK', 'ext_hlth_status': 'OP_STATUS_OK'}

print a

b = {
 "temperature_status": "OP_STATUS_OK",
 "cpu_status": "OP_STATUS_OK",
 "system_health": "OP_STATUS_OK",
 "ext_hlth_status": "OP_STATUS_OK",
}

print b

[root@aikaiyuan control_sh]# python t.py
{'temperature_status': 'OP_STATUS_OK', 'system_health': 'OP_STATUS_OK', 'ext_hlth_status': 'OP_STATUS_OK', 'cpu_status': 'OP_STATUS_OK'}
{'temperature_status': 'OP_STATUS_OK', 'system_health': 'OP_STATUS_OK', 'ext_hlth_status': 'OP_STATUS_OK', 'cpu_status': 'OP_STATUS_OK'}

[root@aikaiyuan control_sh]#

无论手动设置 树形结构,输出还是 一行, 我们可以使用 json.dumps 函数 格式化 树形结构输出,如下。

a = {'temperature_status': 'OP_STATUS_OK', 'cpu_status': 'OP_STATUS_OK', 'system_health': 'OP_STATUS_OK', 'ext_hlth_status': 'OP_STATUS_OK'}

print json.dumps(a, indent=1)

b = {
 "temperature_status": "OP_STATUS_OK",
 "cpu_status": "OP_STATUS_OK",
 "system_health": "OP_STATUS_OK",
 "ext_hlth_status": "OP_STATUS_OK",
}

print json.dumps(b)
[root@aikaiyuan control_sh]# python t.py
{
 "temperature_status": "OP_STATUS_OK",
 "system_health": "OP_STATUS_OK",
 "ext_hlth_status": "OP_STATUS_OK",
 "cpu_status": "OP_STATUS_OK"
}
{"temperature_status": "OP_STATUS_OK", "system_health": "OP_STATUS_OK", "ext_hlth_status": "OP_STATUS_OK", "cpu_status": "OP_STATUS_OK"}
[root@aikaiyuan control_sh]#

转载请注明:爱开源 » Python 字典 格式化输出,树形输出

您必须 登录 才能发表评论!