0

I am storing my column data into Python list, Name of the list should be the same as the column name.

I am using this code:

import mysql.connector as mysql

db = mysql.connect(
    host = "localhost",
    user = "root",
    passwd = "",
    database = "DB"
)
cursor = db.cursor()
query = "SELECT * FROM sample1"
cursor.execute(query)
records = cursor.fetchall()

########  LIST ALL THE COLUMNS ######### 
field_names = [i[0] for i in cursor.description]

#Creating list with column name
for col in field_names:
    exec(col + "=[]")

#appending records into list
for record in records:
    first_name.append(record[0])
    last_name.append(record[1])
    full_name.append(record[2])

If I need to add a new column in future, Again I have to add "abc.append(record[3])".

Is there any way to create the list and append data into it on the fly?

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Abhideep
  • 11
  • 1
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables). A common solution is to use a dictionary to store the data using the *name* for the key. – wwii Apr 30 '19 at 15:42
  • Is there a way to do it by using list?? – Abhideep Apr 30 '19 at 15:46
  • The values of the dictionary can be lists - use a [`collections.defaultdict`](https://docs.python.org/3.7/library/collections.html#collections.defaultdict) for the dictionary. – wwii Apr 30 '19 at 15:51
  • Let me try. Thanks – Abhideep Apr 30 '19 at 16:05

0 Answers0