andrepogg andrepogg - 1 month ago 8
MySQL Question

Python - Extract Values from List of Dictionary (generated by SQL command)

Good Morning,

I'm trying to working with a MySQL DB in Python and I need to extract some data like table names.

So I run this code:

import pymysql.cursors
conn = pymysql.connect(host='myHost', user='user', password='password', db='test', cursorclass=pymysql.cursors.DictCursor)
a = conn.cursor()

sql="SHOW tables like '%s%'"
a.execute(sql)
rows = a.fetchall()
tables = []
for row in rows:
tables.append(row.values())


but when I run
print(tables)
it give me a result like:

["dict_values(['table1'])", "dict_values(['table2'])"]


The only list that I need is
['table1', 'table2', 'etc', 'etc']
.
How can I solve this? It's the SQL statement that cause these kind of problems?

Thank you

Answer

row.values() returns a dict_values object, which acts like a list.

Since you can assume that there's only one value in that list, you can replace this line:

tables.append(row.values())

With this:

tables += row.values()

And you should get the expected result.