Namedtuple problem #32.11.d

Peter Otten __peter__ at web.de
Tue Jun 6 04:30:32 EDT 2017


Deborah Swanson wrote:

>  [{Record}(r0=v0, r1=v1,...,r10=v10,r11='',...r93='') 
  
Lovely column names ;)

> Because, I can't say
> 
> r = r._replace(getattr(r, column) = data)

When r is mutable, i. e. *not* a namedtuple, you can write

setattr(r, column, data)

This assumes column is the column name (a string) -- and it will overwrite 
the current value of the attribute.

If you need the current value as part of a calculation you can access it 
with getattr(). E. g. if you want to multiply columns r.foo and r.bar by a 
value stored in data:

def update_record(record, columnname, data):
    newval = getattr(r, columnname) * data
    setattr(r, columnname, newval)

columns = ["foo", "bar"]
data = 42

for record in records:
    for column in columns:
        update_record(record, column, data)

For immutable (namedtuple) rows this has to be changed:

def updated_record(record, columname, data):
    newval = getattr(r, columnname) * data
    return r._update(**{columnname: newval})

for index, record in enumerate(records):
    for column in columns:
        record = updated_record(record, column, data)
    records[index] = record

There are various approaches to make this clearer. As I have a vage memory 
of recommending `dict`s before I won't do it again...





More information about the Python-list mailing list