【问题标题】:How to write a python dictionary to a json file in the following format? [duplicate]如何将python字典写入以下格式的json文件? [复制]
【发布时间】:2017-03-05 14:34:08
【问题描述】:

所以我有一个 {'key1':[value1, value2]} 形式的 python 字典, 我希望将它写入一个json文件,格式为:

{
   "key1": [value1, value2],
   "key2": [value, value],
   ....
}

我目前使用的是 json.dump(dictionary, file_to_write_to),输出如下:

{"key1": [value1, value2], "key2": [value, value]}

【问题讨论】:

  • json.dump(dictionary, file_to_write_to, indent=4)

标签: python json dictionary


【解决方案1】:

使用此处定义的 json 漂亮打印:

https://docs.python.org/3/library/json.html

【讨论】:

    【解决方案2】:

    来自 simplejson 文档(参见漂亮的打印)https://simplejson.readthedocs.io/en/latest/

    >>> import simplejson as json
    >>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4 * ' '))
    {
        "4": 5,
        "6": 7
    }
    

    【讨论】:

    • 这会产生这样的结果,这不是我所期望的。 `“google.com”:[17.359, 42.282],`
    • 啊,我上面的评论格式搞砸了。基本上 17.359 和 42.282 被分成两行,这不是我所期望的
    猜你喜欢
    • 2012-05-09
    • 2020-07-13
    • 2013-07-13
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 2013-06-14
    相关资源
    最近更新 更多