Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list format from mysqldb

I'm trying to use a Class (adns-python) which is expecting a list in the format:

domain_names = ["google.com", "yahoo.com"]

This is working when I declare the list that way manually. However, I'm trying to use a list returned from mysql using python-mysqldb.

When I look at what is being returned from mysql using:

type(mysql_rows) 

This also shows as a list, but when view the result:

print(mysql_rows) 

I can see the list is in the format:

 [('google.com',), ('yahoo.com',)]

I've tried forcing the output to a list again using list(mysql_rows) which didn't work. I've tried parsing the text manually to make it look like the list using:

text_rows = "[" + ", ".join'"%s"' % i for i in mysql_rows = "]"

Which then shows as the correct format, but it is a string not a list so this doesn't work either.

This is my first few days learning python, so I'm sorry if this is an obvious/stupid question.

Thanks

like image 842
direct00 Avatar asked Feb 07 '12 23:02

direct00


2 Answers

The list is a list of tuples. A simple

lst = [x for x, in mysql_rows]

should be sufficient.

like image 105
Niklas B. Avatar answered Nov 10 '22 04:11

Niklas B.


mysql returns a list of tuples. Each tuple is a result row in your result set. If you want a list of only the first "column" in the result, try this:

first_column = [x[0] for x in mysql_rows]
like image 34
secretmike Avatar answered Nov 10 '22 04:11

secretmike