10.12 Named Tuples

You’ve used tuples to aggregate several data attributes into a single object. The Python Standard Library’s collections module also provides named tuples that enable you to reference a tuple’s members by name rather than by index number.

Let’s create a simple named tuple that might be used to represent a card in a deck of cards. First, import function namedtuple:

In [1]: from collections import namedtuple

Function namedtuple creates a subclass of the built-in tuple type. The function’s first argument is your new type’s name and the second is a list of strings representing the identifiers you’ll use to reference the new type’s members:

In [2]: Card = namedtuple('Card', ['face', 'suit'])

We now have a new tuple type named Card that we can use anywhere a tuple can be used. Let’s 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. The type’s _make class method (that is, a method called on the class) 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')

This could be useful, for example, 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.

For a given object of a named tuple type, you can get an OrderedDict dictionary representation of the object’s member names and values. An OrderedDict 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')])

For additional named tuple features see:

https://docs.python.org/3/library/collections.html#collections.namedtuple

Self Check

  1. (Fill-In) The Python Standard Library’s collections module’s _________ function creates a custom tuple type that enables you to reference the tuple’s members by name rather than by index number.
    Answer: namedtuple.

  2. (IPython Session) Create a namedtuple called Time with members named hour, minute and second. Then, create a Time object, access its members and display its string representation.
    Answer:

    In [1]: from collections import namedtuple
    
    In [2]: Time = namedtuple('Time', ['hour', 'minute', 'second'])
    
    In [3]: t = Time(13, 30, 45)
    
    In [4]: print(t.hour, t.minute, t.second)
    13 30 45
    
    In [5]: t
    Out[5]: Time(hour=13, minute=30, second=45)
    
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.206.169