Often I select data from a SQLite database into a list of dictionaries using something like:
conn.row_factory = sqlite3.Row
c = conn.cursor()
selection = c.execute('select * from myTable')
dataset = selection.fetchall()
dataset1 = [dict(row) for row in dataset]
However, given my database background (Foxpro, SQL-server, etc.) I am more used to using table.column format, which I can get using:
dataset2 = [RowObj(row) for row in dataset]
where
class RowObj(dict):
def __getattr__(self, name):
return self[name]
Question – What is preferable for column value addressing, table[‘column’] or table.column? In my opinion the latter looks neater. Is it just a matter of personal preference, or are there pros+cons of each approach?
I also need to bear-in mind that one day the database might be changed from SQLite to something line mySQL, so I want minimum code changes if/when that happens.
I don’t want to use an ORM package like SQLObject or SQLAlchemy at this stage – not until I am convinced they will benefit my applications.
Regards,
Alan
I fought the
row['column']syntax for a while, but in the end I prefer it. It has two distinct advantages:row['class']is correct syntax, butrow.classis not; keywords cannot directly be used as property names.row.COUNT(*)is obviously not valid syntax, butrow['COUNT(*)']is, etc. (Yes, you could useASin the query to alias, and that’s fine of course. Still, it’s a valid concern.)Having said that, your
RowObjclass of course supports both means of addressing the columns. I’d still prefer consistency though, and if you have aclasscolumn, it’s going to look weird if you address it differently:row.widget, row.dingus, row['class']. (One of these things is not like the other…)