【问题标题】:How can I store each key-value pair of my python dictionary on a separate line in json file?如何将我的 python 字典的每个键值对存储在 json 文件的单独行中?
【发布时间】:2021-12-19 03:45:05
【问题描述】:

我不确定以前是否有人问过这个问题,但我找不到。

我有一个 python 字典,其中所有值都是一个列表。所以,例如:

d = {"car" : ["toyota", "honda"], "bus" : ["hackney", "bombardier"]

当我尝试通过以下方式将其转储到 json 文件时:

with open(output.json, 'w') as f:
   json.dump(d, f)

我明白了:

{
   "car": [
      "toyota",
      "honda"
   ],
   "bus": [
      "hackney",
      "bombardier"
   ]
}

但我希望它看起来像:

{
   "car": [ "toyota", "honda"]
   "bus": [ "hackney", "bombardier"]
}

我尝试使用 indent=2 和 indent=4 但没有运气!有任何想法吗?理想情况下,我希望无需使用任何其他软件包即可完成此任务。

【问题讨论】:

  • 你不能,除非你想写你自己的 JSON 编码器......

标签: python json dump


【解决方案1】:

您可以做到这一点的唯一方法是打印它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    • 2016-11-30
    • 2014-11-19
    相关资源
    最近更新 更多