Python转储dict到json文件 [英] Python dump dict to json file

查看:240
本文介绍了Python转储dict到json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字典:

sample = {'ObjectInterpolator': 1629,  'PointInterpolator': 1675, 'RectangleInterpolator': 2042}



我不知道如何将dict转储到 json 文件,如下所示:

{      
    "name": "interpolator",
    "children": [
      {"name": "ObjectInterpolator", "size": 1629},
      {"name": "PointInterpolator", "size": 1675},
      {"name": "RectangleInterpolator", "size": 2042}
     ]
}

有没有pythonic的方法来做到这一点?

Is there a pythonic way to do this?

您可能想要生成 d3 树形图。

You may guess that I want to generate a d3 treemap.

推荐答案

import json
with open('result.json', 'w') as fp:
    json.dump(sample, fp)

这是一个更简单的方法。

This is an easier way to do it.

第二行代码确定新的json文件的目的地。在这种情况下,文件 result.json 将被创建并在第三行填充:你的dict sample 写入 result.json

The second line of code determines the destination of your new json file. In this case it is the file result.json which will be created and get filled in the third line: Your dict sample gets written into the result.json!

这篇关于Python转储dict到json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆