How to use namedtuples
#import the namedtuple factory method
from collections import namedtuple
#create a namedtuple to represent a Point
Point = namedtuple('Point', ['x', 'y'])
#Create objects from the namedtuple 'Point'
p = Point(3, 4)
#Access the elements using the numeric indices
print(p[0], p[1])
#Access the elements using their names
print(p.x, p.y)
A namedtuple
defined in the collections module is a type of sequence which is similar to a regular tuple
but with some extra features. This data type makes it possible to assign names to each position of the tuple as well as to access values by names rather than just their numeric indices.
Compared to the regular tuples, namedtuples are easier to read and work with, as they allow for more meaningful variable and attribute names. They also use less memory than dictionaries, as they are stored as a single object rather than a collection of key-value pairs.
Similarly to regular tuples, namedtuples are also immutable meaning that they cannot be modified once created.
Instantiating namedtuples
To create namedtuples we start by defining the structure of the tuple using the namedtuple
factory method. This is where we declare the fields that objects of the namedtuple
will contain.We achieve this using the following syntax:
namedtuple('tupleName', ['field1', 'field2', 'field3', ...])
The tupleName
is the name of the namedtuple. The rest of the parameters are strings in an iterable object representing the names of the fields of the namedtuple.
After the structure of the tuple has been established, we then create new objects by assigning a value to each field.
instantiating named tuples
from collections import namedtuple
Person = namedtuple('person', ['name', 'age', 'height'])
p1 = Person('John', 20, 175)
print(p1[0], p1.age, p1.height)
Accessing elements of a namedtuple object
As we have seen from previous examples we can access an element in a namedtuple
through its index or its field name. This is achieved using the dot notation in the case of field names and the square brackets when using index notation.
Access the elements in a namedtuple
using field names
from collections import namedtuple
Person = namedtuple('Person', ['first_name', 'last_name', 'age'])
p1 = Person('John', 'Smith', 30)
# Access elements
print(p1.first_name)
print(p1.last_name)
print(p1.age)
Access the elements in a namedtuple
using index notation
from collections import namedtuple
Person = namedtuple('Person', ['first_name', 'last_name', 'age'])
p1 = Person('Jane', 'Doe', 30)
# Access elements
print(p1[0])
print(p1[1])
print(p1[2])
Operations on namedtuples
Just like in regular tuples, we can perform various arithmetic operations on namedtuples including concatenation and repetition. However, most of these operations will result in a new regular tuple
rather than a namedtuple
object.
Concatenation
Concatenation is when you combine two namedtuples together. This operation results in a new regular tuple with the combined elements of the two namedtuples.
We use the plus(+) for concatenation.
concatenation operation on namedtuples
from collections import namedtuple
Car = namedtuple('Car', 'brand name color')
car1 = Car('Ford', 'Fiesta', 'Blue')
car2 = Car('Honda', 'Accord', 'Red')
#Concatenate two cars
cars = car1 + car2
print(cars)
Repetition
Repetition is repeating the elements of a given namedtuple
for a specified number of times. The operation results in a new regular tuple with the elements of the namedtuple
repeated the number of times specified by the integer operand. We perform this operation using the asterisk(*) operator
repetition operation on namedtuples
#import the namedtuple factory method
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(0, 0)
print(p * 3)
Create a namedtuple from a dict
We can use the double unpacking operator(**) to create a namedtuple
object from dictionary items
Create a namedtuple object from a dictionary
from collections import namedtuple
d = {'name': 'John Doe', 'age': 42, 'country': 'Netherlands'}
Person = namedtuple('Person', d.keys())
p = Person(**d)
print(p)
print(p.name, p.age, p.country)
namedtuple methods and attribute
The namedtuple
class provide some methods that we can use to further manipulate namedtuple
objects.
The methods and attributes can be summarized as shown below.
method | usage |
---|---|
_asdict() |
Returns a copy of the namedtuple in the form of a new dict object |
_make(iterable) |
Creates a new instance of the namedtuple with the values of an iterable given as an argument. |
_replace(**kwrgs) |
Replaces the fields of an existing instance of a namedtuple with the new values provided |
_fiealds |
A tuple containing the field names of the namedtuple |
Get the field names
The _fields attribute
#import the namedtuple factory method
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(0, 0)
print(p._fields)
create a dictionary from a named tuple
The _asdict()
method
#import the namedtuple factory method
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(0, 0)
d = p._asdict()
print(p)
print(d)
Make a named tuple from an iterable
The _make()
method
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age', 'country'])
data = ('Jane', 28, 'Canada')
p = Person._make(data)
print(p.name, p.age, p.country)
Replace the values of a namedtuple
The _replace()
method
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age', 'country'])
data = ('Jane', 28, 'Canada')
p = Person._make(data)
print('old: ', p.name, p.age, p.country)
p = p._replace(name = 'Mary',age = 25, country = 'Finland')
print('new: ', p.name, p.age, p.country)