Exploring Named Tuples (Python)

vegaseat 1 Tallied Votes 1K Views Share

Starting with version 2.6 Python has introduced a new container called the named tuple. You can use it similar to a class based record structure, but it has the memory efficiency of a tuple.

griswolf commented: I appreciate hearing about the new things Python has for us +1
# named tuples have named indexes that behave similar to class 
# instances but require no more memory than regular tuples
# tested with Python 3.1.1 and Python 2.6.5 by vegaseat

import collections as co

# create the named tuple
EmpRec = co.namedtuple('EmpRec', 'name, department, salary')

# load the named tuple and create named indexes
bob = EmpRec('Bob Zimmer', 'finance', 77123)
tim = EmpRec('Tim Bauer', 'shipping', 34231)

# another approach
fred_list = ['Fred Flint', 'purchasing', 42350]
# create a named index from a list
fred = EmpRec._make(fred_list)

# create a named index from an existing named index
john = fred._replace(name='John Ward', salary=49200)

# create a default named index for hourly manufacturing workers
# and apply it to new named indexes
default = EmpRec('addname', 'manufacturing', 26000)
mike = default._replace(name='Mike Holz')
gary = default._replace(name='Gary Wood')
carl = default._replace(name='Carl Boor')

# access by named index
print(bob.name, bob.salary)  # Bob Zimmer 77123
# or access by numeric index
print(tim[0], tim[2])  # Tim Bauer 34231

print('-'*40)

# access from a list of named indexes
emp_list = [bob, fred, tim, john, mike, gary, carl]
for emp in emp_list:
    print( "%-15s works in %s" % (emp.name, emp.department) )

print('-'*40)

# convert a named index to a dictionary via OrderedDict
print( dict(bob._asdict()) )
"""
{'department': 'finance', 'salary': 77123, 'name': 'Bob Zimmer'}
"""

# list the fieldnames of a named index
print(bob._fields)  # ('name', 'department', 'salary')