xralf xralf - 4 years ago 331
Python Question

Select value from list of tuples where condition

I have a list of tuples. Every tuple has 5 elements (corresponding to 5 database columns)
and I'd like to make a query

select attribute1 from mylist where attribute2 = something


e.g.

personAge = select age from mylist where person_id = 10


Is it possible to query the list of tuples in some way?

thank you

Answer Source

If you have named tuples you can do this:

results = [t.age for t in mylist if t.person_id == 10]

Otherwise use indexes:

results = [t[1] for t in mylist if t[0] == 10]

Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _) to unpack a six item tuple.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download