Python Data StructureEnhance your tuples
tuples are lightweight sequences of immutable objects, yet their implementation may prove inconvenient in some scenarios.
collections module provides an enhanced version of a tuple,
namedtuple, that makes member access more natural (rather than using integer indexes).
from collections import namedtuple
point = namedtuple('3DPoint', 'x y z') A = point(x=3, y=5, z=6) print(A) # 3DPoint(x=3, y=5, z=6)
Access a specific member:
print(A.x) # 3
Because namedtuples are backwards compatible with normal tuples, member access can be also done with indexes:
print(A) # 3
To convert a namedtuple to a dict (Actually an
print(A._asdict()) #OrderedDict([('x', 3), ('y', 5), ('z', 6)])
This is a post in the Python Data Structure series.
Other posts in this series: