Python - Tuple Named Tuples

Introduction

Consider the following code

Demo

bob = ('Bob', 40.5, ['dev', 'mgr'])   # Tuple record 
print( bob )

print( bob[0], bob[2] )               # Access by position
# from w  ww . j a v a 2  s .  c o m

Result

Use a dictionary with named fields:

Demo

bob = dict(name='Bob', age=40.5, jobs=['dev', 'mgr'])  # Dictionary record 
print( bob )

print( bob['name'], bob['jobs'] )                               # Access by key
# from  w  ww . ja v a 2 s  . c o  m

Result

We can convert parts of the dictionary to a tuple if needed:

Demo

bob = dict(name='Bob', age=40.5, jobs=['dev', 'mgr'])  # Dictionary record 
print( tuple(bob.values()) )                                    # Values to tuple 
print( list(bob.items()) )                                      # Items to tuple list
# from w  w  w .  j a v a  2  s  . c om

Result

Use named tuple

Demo

from collections import namedtuple                     # Import extension type 
Rec = namedtuple('Rec', ['name', 'age', 'jobs'])       # Make a generated class 
bob = Rec('Bob', age=40.5, jobs=['dev', 'mgr'])        # A named-tuple record 
print( bob )

print( bob[0], bob[2] )                                         # Access by position 
print( bob.name, bob.jobs )                                     # Access by attribute
# from  w  ww .  j a v  a  2 s  . com

Result

Converting to a dictionary supports key-based behavior when needed:

Demo

from collections import namedtuple                     # Import extension type 
Rec = namedtuple('Rec', ['name', 'age', 'jobs'])       # Make a generated class 
bob = Rec('Bob', age=40.5, jobs=['dev', 'mgr'])        # A named-tuple record 
#   w ww . jav a  2s .  c o  m
O = bob._asdict()                                      # Dictionary-like form 
print( O['name'], O['jobs'] )                                   # Access by key too 
print( O )

Result