Consider the following code
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
Use a dictionary with named fields:
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
We can convert parts of the dictionary to a tuple if needed:
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
Use named tuple
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
Converting to a dictionary supports key-based behavior when needed:
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 )