简体   繁体   中英

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:

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

out of two lists which contain titles and ids.

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

I tried it with and a for loop

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:

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

The video value is formed by a list comprehension; for every title, id pair formed by zip() a dictionary is created:

>>> 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:

import json

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM