Background
Python’s namedtuple() is an integral part of the Collections library and an immutable container type.
Values, once set, can not be modified.
You can access values by referencing them via the index or name attribute. The namedtuple() work 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:
Preparation
Before any data manipulation can occur, two (2) new libraries will require installation.
- The Pandas library enables access to/from a DataFrame.
- The Collections library allows storage containers for data structures, such as lists,Β tuples, arrays, dictionaries, etc.
To install these libraries, 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.
$ pip install pandas
Hit the <Enter>
key on the keyboard to start the installation process
$ pip install collections
Hit the <Enter>
key on the keyboard to start the installation process
If the installations were successful, a message displays in the terminal indicating the same.
Feel free to view the PyCharm installation guide for the required libraries.
- How to install Pandas on PyCharm
- How to install Collections on PyCharm
Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.
import pandas as pd import collections
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.
famous_math = collections.namedtuple("Person", ['fname', 'lname', 'DOB', 'IQ']) print(famous_math)
- Line [1] creates the named Tuple
famous_math
and sets up the name and fields. - Line [2] outputs the class object
Person
to the terminal.
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 that 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
. Each mathematician’s first name and IQ are 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.
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
. Each mathematician’s first name and IQ are 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 each record’s field name to the terminal.
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
. - Line [3] outputs the object to the terminal.
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 a namedtuple() is immutable, we will need to replace the existing record with a new one to make a change.
Sophies IQ is incorrect. It is higher than stated. So 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 [2] instantiates a loop with three of the original records and Sophie’s updated record (p5a).
- Line [3] 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()
.
print(p5a._asdict())
Output
{'fname': 'Sophie', 'lname': 'Germain', 'DOB': '04/01/1776', 'IQ': 200}