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
#  w  w  w .j a  va  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
# w  w w. j  ava  2  s  .co  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
#  w w w  .  j  a  v  a2s  .  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 w  w  .  j  a  v a 2 s.co  m

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 
# from w w  w .j  av a  2s.c  o  m
O = bob._asdict()                                      # Dictionary-like form 
print( O['name'], O['jobs'] )                                   # Access by key too 
print( O )

Result