What is the Python version of a MATLAB structure array

Question:

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.

Asked By: ArtDijk

||

Answers:

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.

Answered By: Matti Lyra

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.

Answered By: mikelikespie

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},]
Answered By: chmullig
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.