如何将长字典打印成单独的行

时间:2019-07-12 11:27:52

标签: python dictionary

如何将长字典打印在单独的行中

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

1 个答案:

答案 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"
    }
  ]
}