Looping over elements of named tuple in python

Question:

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))
Asked By: user308827

||

Answers:

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
Answered By: Paweł Kordowski
from collections import namedtuple
point = namedtuple('Point', ['x', 'y'])(1,2)
for k, v in zip(point._fields, point):
    print(k, v)

Output:

x 1
y 2
Answered By: Jano

Python 3.6+

You can simply loop over the items as you would a normal tuple:

MyNamedtuple = namedtuple("MyNamedtuple", "a b")
a_namedtuple = MyNamedtuple(a=1, b=2)

for i in a_namedtuple:
    print(i)

From Python 3.6, if you need the property name, you now need to do:

for name, value in a_namedtuple._asdict().items():
    print(name, value)

Note

If you attempt to use a_namedtuple._asdict().iteritems() it will throw AttributeError: 'collections.OrderedDict' object has no attribute 'iteritems'

Answered By: iamyojimbo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.