0

How can I use colname_1 to get a value for an attribute foo of a namedtuple?

from collections import namedtuple

colname_1 = 'foo'
colname_2 = 'bar'

Farm = namedtuple('Farm', 'foo bar')
farm = Farm('apple', 'banana')

farm.foo  # OK
farm.colname_1  #  of course this doesn't work!
Ryan Kang
  • 61
  • 1
  • 5

1 Answers1

0

Use getattr():

getattr(farm, colname_1) # 'apple'

From the named tuple docs:

To retrieve a field whose name is stored in a string, use the getattr() function

Alternately, although clunky, you can index into the ._fields attribute:

farm[[i for i, f in enumerate(farm._fields) if f == colname_1][0]] # 'apple'
andrew_reece
  • 20,390
  • 3
  • 33
  • 58