1

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?

0

2 Answers 2

2

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.

2
  • It looks really promising but I do not know how to then iterate through the items and put them in the database...
    – Tom
    Commented Jun 6, 2013 at 11:12
  • Here is the link for Mysql operations: tutorialspoint.com/python/python_database_access.htm. All the best!
    – rajpy
    Commented Jun 6, 2013 at 12:25
1

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...
1
  • If you use executemany() it doesn't matter if you use zip() or izip().
    – glglgl
    Commented Jun 6, 2013 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.