如何将长字典打印在单独的行中
test = {'db1': [{'url': 'http://localhost:8080/api', 'cmd': 'test\\nshow databases ', 'request': 'POST'}], 'db2': [{'url': 'http://localhost:8080/api', 'cmd': 'test\\nshow databases ', 'request': 'POST'}]}
预期产量
test =
{'db1':[{'url': 'http://localhost:8080/api', 'cmd': 'test\\nshow databases', 'request': 'POST'}],
'db2': [{'url': 'http://localhost:8080/api', 'cmd': 'test\\nshow databases', 'request': 'POST'}]}
通过导入json模块正在打印给出相同的输出 正常打印(测试)
import json
print (json.dumps(test))
答案 0 :(得分:1)
如果您只是想“漂亮地打印”字典,请使用json.dumps
函数的set the indent
参数:
>>> import json
>>> test = {'db1': [{'url': 'http://localhost:8080/api', 'cmd': 'test\\nshow databases ', 'request': 'POST'}], 'db2': [{'url': 'http://localhost:8080/api', 'cmd': 'test\\nshow databases ', 'request': 'POST'}]}
>>> print(json.dumps(test, indent=2))
{
"db1": [
{
"url": "http://localhost:8080/api",
"cmd": "test\\nshow databases ",
"request": "POST"
}
],
"db2": [
{
"url": "http://localhost:8080/api",
"cmd": "test\\nshow databases ",
"request": "POST"
}
]
}