如何将字典转储到JSON文件中?
如何将字典转储到JSON文件中?
我有一个像这样的字典:
sample = {'ObjectInterpolator': 1629, 'PointInterpolator': 1675, 'RectangleInterpolator': 2042}
我想知道如何将字典转储为以下显示的JSON文件:
{ "name": "interpolator", "children": [ {"name": "ObjectInterpolator", "size": 1629}, {"name": "PointInterpolator", "size": 1675}, {"name": "RectangleInterpolator", "size": 2042} ] }
有没有一种pythonic的方法可以做到这一点?
你可能猜到我想产生一个d3
树状图。
admin 更改状态以发布 2023年5月20日
综合 @mgilson 和 @gnibbler 的答案,我找到了我需要的:
d = { "name": "interpolator", "children": [{ 'name': key, "size": value } for key, value in sample.items()] } j = json.dumps(d, indent=4) with open('sample.json', 'w') as f: print >> f, j
这样,我得到了一个漂亮打印的JSON文件。
诀窍print >> f, j
是从这里找到的:
http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/