Enhance your tuples
Wed May 03, 2017 · 110 words
Python Tuple Named Tuple

Standard Python tuples are lightweight sequences of immutable objects, yet their implementation may prove inconvenient in some scenarios.

Instead, the collections module provides an enhanced version of a tuple, namedtuple, that makes member access more natural (rather than using integer indexes).

Import namedtuple:

from collections import namedtuple

Create a namedtuple object:

point = namedtuple('3DPoint', 'x y z')
A = point(x=3, y=5, z=6)
# 3DPoint(x=3, y=5, z=6)

Access a specific member:

# 3

Because namedtuples are backwards compatible with normal tuples, member access can be also done with indexes:

# 3

To convert a namedtuple to a dict (Actually an OrderedDict):

#OrderedDict([('x', 3), ('y', 5), ('z', 6)])

back · he thought · he could · so he did · main