Reputation: 3
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?
Upvotes: 0
Views: 185
Reputation: 1121942
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)
Upvotes: 4