10.12 Named Tuples

  • Tuples to aggregate several data attributes into a single object
  • collections module provides named tuples
    • Enable you to reference a tuple’s members by name rather than by index number
  • Create a simple named tuple that might be used to represent a card in a deck of cards:
In [1]:
from collections import namedtuple
  • Function namedtuple creates a subclass of the built-in tuple type
  • First argument is your new type’s name
  • Second is a list of strings representing the identifiers used to reference the new type’s members:
In [2]:
Card = namedtuple('Card', ['face', 'suit'])
  • Now have a new tuple type named Card
  • Create a Card object, access its members by name and display its string representation:
In [3]:
card = Card(face='Ace', suit='Spades')
In [4]:
card.face
Out[4]:
'Ace'
In [5]:
card.suit
Out[5]:
'Spades'
In [6]:
card
Out[6]:
Card(face='Ace', suit='Spades')

Other Named Tuple Features

  • Each named tuple type has additional methods
  • _make class method receives an iterable of values and returns an object of the named tuple type:
In [7]:
values = ['Queen', 'Hearts']
In [8]:
card = Card._make(values)
In [9]:
card
Out[9]:
Card(face='Queen', suit='Hearts')
  • Useful if you have a named tuple type representing records in a CSV file
    • As you read and tokenize CSV records, you could convert them into named tuple objects
  • Can get an OrderedDict dictionary representation of a named tuple object’s member names and values
    • Remembers the order in which its key–value pairs were inserted in the dictionary:
In [10]:
card._asdict()
Out[10]:
OrderedDict([('face', 'Queen'), ('suit', 'Hearts')])

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.