Python Named Tuple Methods

Background

The Python’s namedtuple() function is an integral part of the collections library. This function is an immutable container type. Any value, once set, cannot be modified. Access these values via the index or name attribute. The namedtuple() works similar to tuples, however namedtuple() has additional functionality.  This article touches on a few of these methods.

The data type used in this article is a namedtuple() containing two elements:

  • a string
  • a list containing four elements: three string variables and one integer.

Install Required Library

Before any data manipulation can occur, a new library will require installation. This library provides Python access to the collections module.

To install this library, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

Code openpyxl:

 $ pip install collections

Hit the <Enter> key on the keyboard to start the installation process.

If the installation was successful, a message displays in the terminal indicating the same.

Python Declare a Named Tuple

After installing and importing the collections library, the next step is to declare the namedtuple(). Running the code below accomplishes this.

  • Line [1] imports the collections library.
  • Line [2] creates the named tuple famous_math and sets up the name and fields.
  • Line [3] outputs the class object Person to the terminal.

Code:

import collections
famous_math = collections.namedtuple(Person, ['fname', 'lname', 'DOB', 'IQ'])		
print(famous_math)

Output:

<class '__main__.Person>

To view the fields of this namedtuple(), run the following code:

print(famous_math._fields)

Output:

('fname', 'lname', 'DOB', 'IQ')

Python Add Values to Named Tuple

The example below adds four famous mathematicians to the namedtuple() created earlier. If each record added referenced as p1, each line would overwrite the previous one: leaving the last record.

With that in mind, all four lines have different variable names:

p1 = famous_math('Isaac',   'Newton',   '01/04/1643', 190)
p2 = famous_math('Albert',  'Einstein',  '03/14/1879', 205)
p3 = famous_math('Blaise',  'Pascal',      '06/19/1623', 195)
p4 = famous_math('Charles', 'Darwin',   '02/12/1890', 165)

To confirm the above code worked, run the code below.

  • Line [1] instantiates the for loop encapsulating the four records inside a list.
  • Line [2] outputs the record to the terminal.
for p in [p1, p2, p3, p4]:
    print(p)

Output:

Person(fname='Isaac', lname='Newton', DOB='01/04/1643', IQ=190)
Person(fname='Albert', lname='Einstein', DOB='03/14/1879', IQ=205)
Person(fname='Blaise', lname='Pascal', DOB='06/19/1623', IQ=195)  
Person(fname='Charles', lname='Darwin', DOB='02/12/1890', IQ=165)

Python Access Named Tuple by Index or Name

To access a value(s) in a namedtuple(), use index or name. For this example, each mathematician’s first name and IQ output.

Using Index

To access value(s) in namedtuple(), use the index. For this example, each mathematician’s first name and IQ output as a formatted string.

  • Line [1] instantiates the for loop encapsulating the four records inside a list.
  • Line [2] outputs a formatted string referencing the index for the fname and IQ fields to the terminal for each record.

Code:

for p in [p1, p2, p3, p4]:
    print(f"{p[0]}'s IQ is {p[3]}")

Output:

Isaac's IQ is 190.
Albert's IQ is 205. 
Blaise's IQ is 195. 
Charles's IQ is 165.

Using Name

To access value(s) in namedtuple(), use name. For this example, each mathematician’s first name and IQ output as a formatted string.

  • Line [1] instantiates the for loop encapsulating the four records inside a list.
  • Line [2] outputs a formatted string referencing a field name to the terminal for each record.
for p in [p1, p2, p3, p4]:
    print(f"{p.fname}'s IQ is {p.IQ}.")

Output:

Isaac's IQ is 190.
Albert's IQ is 205. 
Blaise's IQ is 195. 
Charles's IQ is 165.

Python Named Tuple _make()

Another way to add a record to a named tuple is _make().

This example adds a mathematician to famous_math named tuple:

P5 = ('Sophie', 'Germain', '04/01/1776', 190)
famous_math._make(p5)
print(famous_math)
  • Line [1] contains the data for the new mathematician.
  • Line [2] creates the record and appends it to famous_math.

Output:

<class '__main__.Person'>

To confirm the record has been added to famous_math, run the following code:

for p in [p1, p2, p3, p4, p5]:
    print(f"{p[0]}'s IQ is {p[3]}.")

Output:

Isaac's IQ is 190.
Albert's IQ is 205.
Blaise's IQ is 195.
Charles's IQ is 165.
Sophie's IQ is 190.

Python Named Tuple _replace()

Since the namedtuple() is immutable, this example replaces an existing record with a new record.

Sophies IQ is incorrect. It is higher than stated. Let’s make that change.

p5a = p5._replace(IQ=200)

for p in [p1, p2, p3, p4, p5a]:
    print(f"{p.fname}'s IQ is now {p.IQ}.")
  • Line [1] replaces the IQ to 200.
  • Line [3] instantiates a loop with three of the original records and Sophie’s updated record (p5a).
  • Line [4] outputs the updated record to the terminal.

Output:

Isaac's IQ is now 190.
Albert's IQ is now 205.
Blaise's IQ is now 195.
Charles's IQ is now 165.
Sophie's IQ is now 200.

The records in the list now contain p5a. This record reflects the new IQ.

Python Named Tuple _asdict()

This method returns an OrderedDict() from the mapped values of a namedtuple(). For this example, the record for Sophie converts to an OrderedDict().

Code:

print(p5a._asdict())

Output:

{'fname': 'Sophie', 'lname': 'Germain', 'DOB': '04/01/1776', 'IQ': 200}