Parse variable into variables >Re: Apology

Delaney, Timothy tdelaney at avaya.com
Tue Feb 26 23:40:39 EST 2002


> From: Jason Orendorff [mailto:jason at jorendorff.com]
> 
> Timothy Rue wrote:
> > vic['AI']['1'], vic['AI']['2'], vic['AI']['3'] = varset.split()
> >
> > is there a way to add the readline() into this line?
> > ..... = testfile.readline().split()
> 
> All of this is correct.  You might even want to just do:
> 
>   vic['AI'] = testfile.readline().split()
> 
> but of course that makes vic['AI'] a list of strings,
> not a dictionary.  Which may or may not be okay.

However, it can also be confusing.

The way I would do it would be (using a better indexed() though - generators
:)

def indexed (seq, start=0):
    return map(None, range(start, len(seq) + start), seq)

line = testfile.readline()
tokens = line.split()

for i, token in indexed(tokens, 1):
    vic['AI'][str(i)] = token

This fits your first line, but in a more general (it allows an unknown
number of tokens) and much easier-to-read way. Of course, whether you really
want a dictionary of dictionaries I don't know ... (I suspect you actually
want a list of tokens, in which case you should just put tokens into your
vic dictionary).

Always go for the most readable way first - you will appreciate it when you
have to go back and work out what you have done.

As you can see, as soon as you start showing that you've done some work,
people become much more responsive.

Tim Delaney




More information about the Python-list mailing list