Reputation: 2017
I am new to Python. I want to put the result of a SQL query in a sort of matrix variable like the structure array of MATLAB. Basically a matrix that holds numbers and strings.
The variable then holds the rows and columns of the query.
How can I do this?
Thanks.
Upvotes: 2
Views: 2066
Reputation: 5842
If you want just matrices and vectors like MATLAB, your best bet is NumPy (and SciPy if you want more MATLABby features)
Also if you want to make sexy plots, I recommend Matplotlib.
Upvotes: 3
Reputation: 13416
If @Matti's answer isn't what you want, perhaps a list of dictionaries would do it?
select field1, field2, field3 from SomeTable
That would then be converted to something like:
[{'field1' : 1, 'field2' : 'asdf', 'field3' : 3.234},
{'field1' : 0, 'field2' : 'Some string here', 'field3', 0.93284},]
Upvotes: 1
Reputation: 13088
I trust you have already discovered MySQLdb for getting the stuff from the database into Python. That will by default return an array of tuples which you can iterate over. If you want a data structure that you can access by key (as the matlab struct) then you'll need to use a dictionary in Python.
A query like
"Select field1,field2 FROM SomeTable"
Will get you the following
[(field1,field2),(field1,field2),(field1,field2)]
If a list of tuples is not what you want, you can either use a different type of MySQLdb cursor (see the docs) or iterate over the list of tuples and convert it to something else.
Upvotes: 2