41

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))
user308827
  • 21,227
  • 87
  • 254
  • 417

3 Answers3

51

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
Paweł Kordowski
  • 2,688
  • 1
  • 14
  • 21
7
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
Jano
  • 71
  • 1
  • 1
7

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'

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
iamyojimbo
  • 4,233
  • 6
  • 32
  • 39