Newbie Question: Obtain element from list of tuples

Chris Angelico rosuav at gmail.com
Sun Dec 18 18:40:06 EST 2011


On Mon, Dec 19, 2011 at 9:55 AM, HoneyMonster <someone at someplace.invalid> wrote:
> When the user selects a row and clicks a button, I am using:
> pos = self.grid_1.GetGridCursorRow() to establish which tuple in recs is
> involved, and then pid = recs[pos][4] to determine the key value (I
> suspected that accessing recs directly would be more efficient that
> trying to determine the wxGrid column value, and in any case the pid is
> in recs but not in the wxGrid).

Yep, this looks like a sensible way to do it!

I would recommend, though, that you avoid "magic numbers" - the
process ID might happen to be in cell 4, but what if your column list
changes? This is especially problematic when you use "select * from
table", because changes outside your code can break things.

There's two solutions. One is to carefully match your SELECT statement
to a set of constants:

exec("SELECT FOO,BAR,QUUX,ASDF,PID,WHATEVER FROM table")
FOO,BAR,QUUX,ASDF,PID,WHATEVER,*_=range(20) # Cool trick to avoid
having to count the columns

But a better way is to let the database handle it. Check your
interface library to see if you can have it return dictionaries or
objects instead of tuples - then you could use:

pid = recs[pos]["pid"]
# or
pid = recs[pos]->pid

which avoids the need to count columns at all.

Other than that, though, yep - your code concept looks fine.

ChrisA



More information about the Python-list mailing list