我有一个这样的字典:

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

我不知道如何转储字典到一个JSON文件如下所示:

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

有蟒式的方法吗?

您可能猜到我想要生成一个d3树图。


当前回答

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

从python 3.7开始,字典的顺序被保留https://docs.python.org/3.8/library/stdtypes.html#mapping-types-dict

字典保持插入顺序。注意,更新密钥不会影响顺序。删除后添加的键在最后插入

其他回答

如果你使用Path:

example_path = Path('/tmp/test.json')
example_dict = {'x': 24, 'y': 25}
json_str = json.dumps(example_dict, indent=4) + '\n'
example_path.write_text(json_str, encoding='utf-8')

结合@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文件。 打印>> f, j从这里找到: http://www.anthonydebarros.com/2012/03/11/generate-json-from-sql-using-python/

d = {"name":"interpolator",
     "children":[{'name':key,"size":value} for key,value in sample.items()]}
json_string = json.dumps(d)

从python 3.7开始,字典的顺序被保留https://docs.python.org/3.8/library/stdtypes.html#mapping-types-dict

字典保持插入顺序。注意,更新密钥不会影响顺序。删除后添加的键在最后插入

这应该是一个开始

>>> import json
>>> print json.dumps([{'name': k, 'size': v} for k,v in sample.items()], indent=4)
[
    {
        "name": "PointInterpolator",
        "size": 1675
    },
    {
        "name": "ObjectInterpolator",
        "size": 1629
    },
    {
        "name": "RectangleInterpolator",
        "size": 2042
    }
]

还想添加这个(Python 3.7)

import json

with open("dict_to_json_textfile.txt", 'w') as fout:
    json_dumps_str = json.dumps(a_dictionary, indent=4)
    print(json_dumps_str, file=fout)

更新(11-04-2021):所以我添加这个例子的原因是因为有时你可以使用print()函数写入文件,这也展示了如何使用缩进(无缩进的东西是邪恶的!!)然而,我最近开始学习线程,我的一些研究表明,print()语句并不总是线程安全的。所以如果你需要线程,你可能要小心这个。