Re: Lists of lists and tuples, and finding things within them
- From: "Daniel Nogradi" <nogradi@xxxxxxxxx>
- Date: Thu, 9 Nov 2006 19:06:52 +0100
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', 'dragonstone.org'), ('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', 'dragonstone.org'))).
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:
mydict = dict( password01='unk', host='dragonstone.org', port='1234',
character01='Thessalus' )
And then you would look up host by:
mydict[ 'host' ]
HTH,
Daniel
.
- Follow-Ups:
- Re: Lists of lists and tuples, and finding things within them
- From: attn . steven . kuo
- Re: Lists of lists and tuples, and finding things within them
- From: dakman@xxxxxxxxx
- Re: Lists of lists and tuples, and finding things within them
- Prev by Date: Newb: installing Jython on Windows XP ...
- Next by Date: Re: Vim/Python Help
- Previous by thread: Newb: installing Jython on Windows XP ...
- Next by thread: Re: Lists of lists and tuples, and finding things within them
- Index(es):
Relevant Pages
|