Looping over elements of named tuple in python

30,167

Solution 1

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

Solution 2

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

Solution 3

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'

Share:
30,167
user308827
Author by

user308827

Updated on December 29, 2021

Comments

  • user308827
    user308827 over 2 years

    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
    user308827 over 8 years
    thanks @Pawel, good point re immutability. Any way you can adapt your response to my specific code?
  • Paweł Kordowski
    Paweł Kordowski over 8 years
    just replace a with self.CTFs
  • r0f1
    r0f1 over 7 years
    This seems to be working though in Python 3.6: a._asdict().items()
  • Jonathan H
    Jonathan H about 6 years
    @ThorSummoner _asdict is a function, not a property. Could you please delete your comment? It is misleading.
  • jtlz2
    jtlz2 over 4 years
    .iteritems() -> .items() for python3