namedtuple in Python

The namedtuple class in Python is a container that holds other elements. With namedtuple class, different tuple types with names can be created and the fields of the tuple as well can have names.

Namedtuple Updated 14 Nov 2019 1 min read

Overview

  • Like the tuple class, namedtuple is also a container in Python.
  • New tuple types can be created by simply passing the name of the type, using the class namedtuple.
  • With namedtuple two types of names are created for a tuple:
    • A name for the new tuple type
    • Names for the tuple fields
  • Often CSV files, Relational Database Tables have headers/column names for the data. Tuple objects with named fields map seamlessly to such data.
  • A namedtuple can be converted to a Python dict using the method _asdict().
  • The class namedtuple itself is derived from the Python tuple class.

Example – Making namedtuple instances from a CSV file

The Python example reads the contents of the following CSV file and populates the namedtuple with the name AfterSalesRecord.

CSV File

python
# Example Python program that reads records from a CSV file

# and populates them into Python namedtuple instances

import collections as coll

import csv

# Create a new tuple type with the name AfterSalesRecord

SalesRecord = coll.namedtuple('AfterSalesRecord', 'make, units, totalusd');

# Create a CSV reader

csvReader   = csv.reader(open("car_aftersales.csv", "r"));

# Make a namedtuple for each record from the CSV file

print("Contents of the CSV file:");

for sales in map(SalesRecord._make, csvReader):

    print(sales.make, sales.units, sales.totalusd);

Output

Output
Contents of the CSV file:

make  units  totalusd

m1  5  35000

m2  7  32000

m3  2  12000

m4  4  15000

m5  10  67000

m6  8  64000

m7  5  50000

m8  4  80000

m8  4  80000