Creating named tuples in Python
Named tuples are an interesting, flexible and fun data structure in Python.
Sorta like an openstruct in Ruby, it's a quick way to create a finite data structure that has named properties. The properties of a namedtuple are also accessible via index.
from collections import namedtuple
Thing = namedTuple('Thing', ['a', 'b'])
x = Thing(1, 2)
x.a
# 1
x[0]
# 1
You can create an instance of a named tuple with named arguments as well.
x = Thing(b=3, a=4)
# Thing(a=4, b=3)
The properties of a namedtuple can also be declared with a string rather than a list. That looks like this:
Row = namedtuple('Row', 'a b c d')
or comma separated:
Row = namedtuple('Row', 'a, b, c, d')
Tweet