How to fetch data in Python from SQL as a list of strings instead of tuples?
Question:
I’m trying to get the columns names of an SQLite table, but I’m getting back a list of tuples with the names.
cur.execute('''SELECT name FROM PRAGMA_TABLE_INFO('Emails')''')
.fetchall())
If I print this the output is:
[('email',), ('count',)]
How can I get the data as list of strings?
Answers:
You can extract the column names out of each tuple to a new list:
result = cur.execute("SELECT name FROM PRAGMA_TABLE_INFO('Emails')").fetchall()
columns = [x[0] for x in result]
print(columns)
Or, get the column names as a comma separated srring with GROUP_CONCAT()
and then split it:
result = cur.execute("SELECT GROUP_CONCAT(name) FROM PRAGMA_TABLE_INFO('Emails')").fetchone()
columns = str(result[0]).split(",")
print(columns)
Output:
['email', 'count']
I’m trying to get the columns names of an SQLite table, but I’m getting back a list of tuples with the names.
cur.execute('''SELECT name FROM PRAGMA_TABLE_INFO('Emails')''')
.fetchall())
If I print this the output is:
[('email',), ('count',)]
How can I get the data as list of strings?
You can extract the column names out of each tuple to a new list:
result = cur.execute("SELECT name FROM PRAGMA_TABLE_INFO('Emails')").fetchall()
columns = [x[0] for x in result]
print(columns)
Or, get the column names as a comma separated srring with GROUP_CONCAT()
and then split it:
result = cur.execute("SELECT GROUP_CONCAT(name) FROM PRAGMA_TABLE_INFO('Emails')").fetchone()
columns = str(result[0]).split(",")
print(columns)
Output:
['email', 'count']