Lists of lists and tuples, and finding things within them

attn.steven.kuo at attn.steven.kuo at
Thu Nov 9 21:27:10 CET 2006

Daniel Nogradi wrote:
> > I have a program that keeps some of its data in a list of tuples.
> > Sometimes, I want to be able to find that data out of the list.  Here is
> > the list in question:
> >
> > [('password01', 'unk'), ('host', ''), ('port', '1234'),
> > ('character01', 'Thessalus')]
> >
> > For a regular list, I could do something like x.index('host') and find
> > the index of it, but I don't know how to do this for a tuple where the
> > data item isn't known in advance.  For example, I want to get the "host"
> > entry from the list above; but I can only retrieve it if I know what it
> > contains (e.g., x.index(('host', ''))).
> >
> > Is there a better way to do this than a construct similar the following?
> >
> > for key, value in x:
> >     if key == 'host':
> >         print value
> >
> If I were you I would use a dictionary for such a thing:


The sequence of tuples may have repeated "keys"; if
that's the case, then you may use a filter/iterator instead.
Using a dictionary would otherwise cause you to lose

import itertools

mytuple = (('foo', 'bar'), ('foo', 'foobar'), ('baz', 'qux'))

it = itertools.ifilter(lambda t : t[0] == 'foo', mytuple)
for t in it:
    print t

Hope this helps,

More information about the Python-list mailing list