Using namedtuples field names for column indices in a list of lists

Deborah Swanson python at deborahswanson.net
Sun Jan 8 00:39:47 EST 2017


What I've done so far:

with open('E:\\Coding projects\\Pycharm\\Moving\\Moving 2017 in.csv',
'r') as infile:
	ls = list(csv.reader(infile))
lst = namedtuple('lst', ls[0])

where 'ls[0]' is the header row of the csv, and it works perfectly well.
'lst' is a namedtuple instance with each of the column titles as field
names. 

And retrieving values also works:

if len(lst.Location.fget(l)) == 0:
	.
	.

Using the .fget method for each field name returns the value in the row
and column, here row 'l' and column 'Location'.

So far so good. 'lst.Location.fget(l)' is clunkier than l[lo], but it's
recognizable and it works.

But I haven't found a way to assign new values to a list element. using
namedtuple.fieldname. I think a basic problem is that namedtuples have
the properties of tuples, and you can't assign to an existing tuple
because they're immutable. Also there's the matter of
namedtuple.fieldname being a property and not an index integer, so it
doesn't work if you try to use them as indices.

If I try:    

l[lst.Location] = 'xyz'     ('l' is a list)

I get: TypeError: list indices must be integers, not property

I'm a little hopeful that namedtuples has a built-in solution. In
addition to the method fget, each field name also has a property fset:

fset = {NoneType}None

But I can't find anything in the documentation that tells what fset is
and how to use it.

Another possibility would be to map index integers to the field names in
the namedtuple, in a way that could be accessed using the namedtuple's
field names. I've looked into using map(), but the documentation is so
sketchy I couldn't see a way to do this from what is given.  And
google's no help. If anyone else has tried to do this, google can't find
it. They don't have a string of words that I could find preloaded into
their "AI" code that will turn up anything close. Most search attempts
just ignored all my search terms except 'namedtuples' and returned
general stuff on namedtuples. I looked through a few of them, but
nothing I looked at gave any useful solution to this problem. 

Anybody know how to use .fset?  Or a way to assign to list locations by
their namedtuples fieldnames and list rows?




More information about the Python-list mailing list