How to access a field of a namedtuple using a variable for the field name?

LangeHaare picture LangeHaare · Jun 19, 2017 · Viewed 24k times · Source

I can access elements of a named tuple by name as follows(*):

from collections import namedtuple
Car = namedtuple('Car', 'color mileage')
my_car = Car('red', 100)
print my_car.color

But how can I use a variable to specify the name of the field I want to access? E.g.

field = 'color'
my_car[field] # doesn't work
my_car.field # doesn't work

My actual use case is that I'm iterating through a pandas dataframe with for row in data.itertuples(). I am doing an operation on the value from a particular column, and I want to be able to specify the column to use by name as a parameter to the method containing this loop.

(*) example taken from here. I am using Python 2.7.

Answer

juanpa.arrivillaga picture juanpa.arrivillaga · Jun 19, 2017

You can use getattr

getattr(my_car, field)