[ Python lists into MySQL Database ]
I have a question and I am actually already struggling with the approach how to tackle it. I have several lists.
name = ['name1','name2', 'name3']
id = ['id1', 'id2', 'id3']
created_at = ['created_at1', 'created_at2', 'created_at3']
The lists have always the same number of element. What I want to do is write them into a MySql database that looks like this:
Name ID Created_at
name1 id1 created_at1
name2 id2 created_at2
name3 id3 created_at3
Any ideas?
Answer 1
Use zip.
output = zip(name, id, created_at)
output: [('name1', 'id1', 'created_at1'), ('name2', 'id2', 'created_at2'), ('name3', 'id3', 'created_at3')]
Iterate through the output and insert into the database.
updated: Iterating through output:
for item in output:
=== Have to do mysql insert operation ===
Hope it helps.
Answer 2
Iterating through multiple lists at the same time is what zip
(and even better, itertools.izip
) are for.
for each_name, each_id, each_created_at in itertools.izip(name, id, created_at):
... insert into db...