如何从Python中的列表中创建JSON文件?

时间:2014-12-19 19:25:36

标签: python json python-3.x dictionary

我尝试制作一个看起来像这样的有效JSON文件:

{
    "video": [
      {"title": "New", "id": "123"},
      {"title": "New", "id": "123"}
    ]
  }

两个包含标题和ID的列表。

titles = ['New', 'New']
ids = ['123', '123']

我尝试了和for循环

key[] = value

但它只给了我最后两项。

我也尝试了

newids = {key:value for key, value in titles}

哪个也行不通。

有人可以给我建议怎么做吗?

1 个答案:

答案 0 :(得分:4)

使用zip()配对列表:

{'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}

video值由列表推导形成;对于由title, id形成的每个zip()对,都会创建一个字典:

>>> titles = ['New', 'New']
>>> ids = ['123', '123']
>>> {'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}
{'video': [{'title': 'New', 'id': '123'}, {'title': 'New', 'id': '123'}]}

或者有一些更有趣的内容:

>>> from pprint import pprint
>>> titles = ['Foo de Bar', 'Bring us a Shrubbery!', 'The airspeed of a laden swallow']
>>> ids = ['42', '81', '3.14']
>>> pprint({'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]})
{'video': [{'id': '42', 'title': 'Foo de Bar'},
           {'id': '81', 'title': 'Bring us a Shrubbery!'},
           {'id': '3.14', 'title': 'The airspeed of a laden swallow'}]}

如果您还不知道如何使用json library将结果编码为JSON,请写入文件使用:

import json

with open('output_filename.json', 'w', encoding='utf8') as output:
    json.dump(python_object, output)