Looping over elements of named tuple in python

user308827 picture user308827 · Nov 29, 2015 · Viewed 25.3k times · Source

I have a named tuple which I assign values to like this:

class test(object):
            self.CFTs = collections.namedtuple('CFTs', 'c4annual c4perren c3perren ntfixing')

            self.CFTs.c4annual = numpy.zeros(shape=(self.yshape, self.xshape))
            self.CFTs.c4perren = numpy.zeros(shape=(self.yshape, self.xshape))
            self.CFTs.c3perren = numpy.zeros(shape=(self.yshape, self.xshape))
            self.CFTs.ntfixing = numpy.zeros(shape=(self.yshape, self.xshape))

Is there a way to loop over elements of named tuple? I tried doing this, but does not work:

for fld in self.CFTs._fields:
                self.CFTs.fld= numpy.zeros(shape=(self.yshape, self.xshape))

Answer

Paweł Kordowski picture Paweł Kordowski · Nov 29, 2015

namedtuple is a tuple so you can iterate as over normal tuple:

>>> from collections import namedtuple
>>> A = namedtuple('A', ['a', 'b'])
>>> for i in A(1,2):
    print i


1
2

but tuples are immutable so you cannot change the value

if you need the name of the field you can use:

>>> a = A(1, 2)
>>> for name, value in a._asdict().iteritems():
    print name
    print value


a
1
b
2

>>> for fld in a._fields:
    print fld
    print getattr(a, fld)


a
1
b
2