Looping over elements of named tuple in python
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
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'
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