Parse variable into variables >Re: Apology

Jeff Shannon jeff at ccvcorp.com
Wed Feb 27 13:24:44 EST 2002


Joshua Muskovitz wrote:

> > testfile = open('test','r')
> > varset = testfile.readline()
> > tple = varset.split()
> > vic['AI']['1'], vic['AI']['2'], vic['AI']['3'] = tple
> > I assume this will work???
>
> Almost.
>
> vic = {}
> testfile = open('test','r')
> varset  = testfile.readline()
> tple = varset.split()
> vic[('AI','1')], vic[('AI','2')], vic[('AI','3')] = tple
> testfile.close() # don't forget to clean up after yourself

Actually, your sematics are slightly different.  In

vic['AI']['1'], vic['AI']['2'], vic['AI']['3'] = tple

vic['AI'] is a dictionary, and we're creating keys '1', '2', and '3'.  One
could presumably also have a vic['IQ'] dictionary, etc -- in other words, vic
itself is a dictionary of dictionaries.  In your example, you're creating a
single dictionary, which is keyed on tuples of ('AI', ...), and presumably at
some point ('IQ', ...), etc.  This may not be the best way to deal with it.
Since each chunk (AI, IQ, etc..) is conceptually different, having them as
separate dictionaries seems reasonable -- using them as the first element of a
key-tuple seems to me to be a bit obscure.  And Tim's usage *will* work,
provided that the dictionaries are set up properly beforehand:

vic = { 'AI': {}, 'IQ': {}, .... }

Actually, it might (or might not) make more sense to use a dictionary of lists,
i.e.

vic = { 'AI': [], 'IQ': [], ...}
...
vic['AI'].extend( list(tple) )  #convert the tuple to list before extend can
work

... wait, actually, since split() returns a list, the list call isn't needed
after all.  (Despite being called 'tuple unpacking', it also works on lists.)
So this can be simplified to

vic['AI'].extend( tple )

Doing this additionally allows a variable number of elements in tple -- you no
longer throw an exception if it's not exactly the number you expect.  (Whether
this is good or bad depends on your intent -- if you *want* to enforce
three-element lines, you can check len(tple) and raise an exception yourself.)


> and yes, you can shorten the entire thing down to:
>
> vic[('AI','1')], vic[('AI','2')], vic[('AI','3')] =
> open('test','r').readline().split()

Of course, by doing this, you're only getting the first line of the file.  If
one presumes that the rest of the file will be processed, too, then this isn't
a very good way of doing things.  ;)  I think that chaining in the open() call
is a bad idea, therefore; but the rest of the chaining works just fine.

infile = open('test.txt', 'r')
...
vic['AI'].extend( infile.readline().split() )
...
infile.close()


Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list