Cleaning up conditionals

Deborah Swanson python at
Mon Jan 2 19:53:11 EST 2017

Gregory Ewing wrote, on Monday, January 02, 2017 3:28 PM
> Deborah Swanson wrote:
> > flds = len(ls[0])
> > cl, ur, d1, de, lo, st, mi, ki, re, da, br, no, yn, ma, ar =
> > range(0,flds)
> You might like to consider converting the row into a 
> namedtuple, then you could refer to the fields using 
> attribute names instead of indexes.
> You could even use the header row to set up the field
> names in the namedtuple, so if you reorder the columns
> in the file, the code would automatically adapt.
> -- 
> Greg

I actually tried putting them into a list early on, but the problem was
that it didn't do its main job, which is to help me avoid having to
rewrite code everytime the columns change. Once you put the field names
or codes into any kind of sequence, they can no longer be used as scalar
indices without rewriting code to use their new indices in the tuple or
list. Not really any kind of major improvement over counting out each
one's position in the row.

Unless you know of, and are suggesting, a way to index a sequence with
strings instead of integers, so the code could remain untouched with
string indices when changes to the columns are made. Certainly might be
possible, I simply haven't and probably wouldn't have thought of it
since what I have works and I've got tons of other stuff to do.

So here's the new question: Is it possible to index a sequence with
strings instead of integers?  (Dictionaries excluded because dicts are
not sequentially ordered in python 3.5 and earlier. Although, I've read
that they will be in 3.6 or beyond.)

Also, for such a scheme to be superior to what I already have, it needs
to be very nearly self-maintaining. I only touch the 2nd of those two
lines when I'm adding or deleting columns.

More information about the Python-list mailing list