[英]How do I make a JSON file out of a list in Python?
I try to make a valid JSON file which supposed to look like this one: 我尝试制作一个看起来像这样的有效JSON文件:
{
"video": [
{"title": "New", "id": "123"},
{"title": "New", "id": "123"}
]
}
out of two lists which contain titles and ids. 在两个包含标题和ID的列表中。
titles = ['New', 'New']
ids = ['123', '123']
I tried it with and a for loop 我尝试了和for循环
key[] = value
But it only gives me the last two items. 但这仅给了我最后两项。
I also tried it with 我也尝试过
newids = {key:value for key, value in titles}
Which also does not work. 这也行不通。
Can someone give me advice how to do it? 有人可以给我建议怎么做吗?
Use zip()
to pair up the lists: 使用zip()
配对列表:
{'video': [{'title': title, 'id': id} for title, id in zip(titles, ids)]}
The video
value is formed by a list comprehension; video
值由列表推导形成; for every title, id
pair formed by zip()
a dictionary is created: 对于每个title, id
由zip()
组成的title, id
对将创建一个字典:
>>> 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'}]}
or with a little more interesting content: 或更有趣的内容:
>>> 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'}]}
In case you also don't know how to then encode the result to JSON with the json
library , to write to a file use: 如果您还不知道如何使用json
库将结果编码为JSON,以使用以下方法写入文件:
import json
with open('output_filename.json', 'w', encoding='utf8') as output:
json.dump(python_object, output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.