1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can go with this code the only thing ou have to keep in mind is this tables.append(row.values()[0]) syntax cause you using the values of dictionary

import pymysql.cursors
conn = pymysql.connect(host='myHost', user='user', password='password', db='test', cursorclass=pymysql.cursors.DictCursor)
a = conn.cursor()
sql="SHOW tables"
a.execute(sql)
tables = []
rows = a.fetchall()
for row in rows:
    tables.append(list(row.values())[0])

2 Comments

It return: TypeError: 'dict_values' object does not support indexing
In python 3 row.values() returns view instead of list so you can change the last line to this tables.append(list(row.values())[0]) @andrepogg

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.