Home > OS >  Parse list items between two lists with the same index and store in database
Parse list items between two lists with the same index and store in database

Time:01-27

I am beginner in Python. I am struggling to save in a mysql table id and respective comment.comment codes are saved in a list, the same hapen for comment texts too. I want to save each code and comment in a row database as below:

id     content
 1       A
1.5      B
 3       C

.........

Below is a snippet of my source code:

cursor = self.con.cursor()

cursor.execute("select id from news where uri = %s", (item['article_url'],))
result = cursor.fetchone()


my_list = [{'comment_code': ['1','18','2','3','4','5','6','7','8','9','10'],
        'comment_text': ['A', 'B', 'C', 'D','E','F','G','H','I','J','K']}]

for cit in my_list:
    cursor.execute(""" insert into comment (id,content) values (%s,%s)""",
                       (cit["comment_code"], cit["comment_text"]))
    self.con.commit()

How can I Parse list items between two lists with the same index and store in database?

CodePudding user response:

One possible solution would be to use zip() to iterate over both lists in pairs. zip() will combine them in a single iterable like this:

cursor = self.con.cursor()

cursor.execute("select id from news where uri = %s", (item['article_url'],))
result = cursor.fetchone()

my_list = [{'comment_code': ['1','18','2','3','4','5','6','7','8','9','10'],
        'comment_text': ['A', 'B', 'C', 'D','E','F','G','H','I','J','K']}]

for code, text in zip(my_list[0]['comment_code'], my_list[0]['comment_text']):
    cursor.execute(""" insert into comment (id,content) values (%s,%s)""", (code, text))
    self.con.commit()

CodePudding user response:

does your id has auto_increment ?

  • Related