【问题标题】:How to print the long dictionary in to seperate lines [duplicate]如何将长字典打印成单独的行[重复]
【发布时间】:2019-11-22 04:03:46
【问题描述】:

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

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

【问题讨论】:

  • 使用pprint.pprint(test)?
  • 如果您只想每行打印一个键值对,可以使用:for k,v in test.items(): print('%s: %s' % (k, v))

标签: python dictionary


【解决方案1】:

如果你只是想“漂亮地打印”你的字典,set the indent 函数的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"
    }
  ]
}

【讨论】:

    猜你喜欢
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2019-07-02
    相关资源
    最近更新 更多