Open In App

Namedtuple in Python

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python supports a type of container dictionary called “namedtuple()” present in the module “collections“. In this article, we are going to see how to Create a NameTuple and operations on NamedTuple.

What is NamedTuple in Python?

In Python, NamedTuple is present inside the collections module. It provides a way to create simple, lightweight data structures similar to a class, but without the overhead of defining a full class. Like dictionaries, they contain keys that are hashed to a particular value. On the contrary, it supports both access from key-value and iteration, the functionality that dictionaries lack.

Python NamedTuple Syntax

namedtuple(typename, field_names)

  • typename – The name of the namedtuple.
  • field_names – The list of attributes stored in the namedtuple.

Example: Code implementation of NamedTuple is shown in Python.

Python3
# Python code to demonstrate namedtuple()
from collections import namedtuple

# Declaring namedtuple()
Student = namedtuple('Student', ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# Access using index
print("The Student age using index is : ", end="")
print(S[1])

# Access using name
print("The Student name using keyname is : ", end="")
print(S.name)

Output
The Student age using index is : 19
The Student name using keyname is : Nandini

Operations on NamedTuple

Below are the following operations that can done by using namedtuple():

  • Create a NameTuple
  • Access Operations
  • Conversion Operations
  • Additional Operations

Create a NameTuple in Python

This creates a new namedtuple class using the namedtuple() function from the collections module. The first argument is the name of the new class, and the second argument is a list of field names.

Python3
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(x=1, y=2)
print(p.x, p.y) 

Output
1 2

Access Operations

Namedtuples in Python provide convenient ways to access their fields. Below are some access operations provided in Python for NamedTuple:

  • Access by index
  • Access by keyname
  • Access Using getattr()

Access By Index

The attribute values of namedtuple() are ordered and can be accessed using the index number unlike dictionaries which are not accessible by index. In this example, we are accessing the student’s by using index.

Python3
# importing "collections" for namedtuple()
import collections

# Declaring namedtuple()
Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# Access using index
print("The Student age using index is : ", end="")
print(S[1])

Output
The Student age using index is : 19

Access by keyname

Access by keyname is also allowed as in dictionaries. In this example, we are using keyname to access the student’s name.

Python3
# importing "collections" for namedtuple()
import collections

# Declaring namedtuple()
Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# Access using name
print("The Student name using keyname is : ", end="")
print(S.name)

Output
The Student name using keyname is : Nandini

Access Using getattr()

This is yet another way to access the value by giving namedtuple and key value as its argument. In this example, we are using getattr() to access the student’s id in the given namedtuple.

Python3
# importing "collections" for namedtuple()
import collections

# Declaring namedtuple()
Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# Access using getattr()
print("The Student DOB using getattr() is : ", end="")
print(getattr(S, 'DOB'))

Output
The Student DOB using getattr() is : 2541997

Conversion Operations

Namedtuples provide a few useful conversion operations to work with other data types in Python. Below are the following conversion operations that is provided for namedtuples in Python:

  • Using _make()
  • Using _asdict()
  • Using “**” (double star) operator

Conversion Using _make()

This function is used to return a namedtuple() from the iterable passed as argument. In this example, we are using _make() to convert the list “li” into namedtuple.

Python3
# importing "collections" for namedtuple()
import collections

# Declaring namedtuple()
Student = collections.namedtuple('Student',
                                 ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# initializing iterable
li = ['Manjeet', '19', '411997']

di = {'name': "Nikhil", 'age': 19, 'DOB': '1391997'}

# using _make() to return namedtuple()
print("The namedtuple instance using iterable is  : ")
print(Student._make(li))

Output
The namedtuple instance using iterable is  : 
Student(name='Manjeet', age='19', DOB='411997')

Conversion Operation Using _asdict()

This function returns the OrderedDict() as constructed from the mapped values of namedtuple(). In this example, we are using _asdict() to convert the input list into namedtuple instance.

Python3
import collections
# Declaring namedtuple()
Student = collections.namedtuple('Student',
                                 ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# initializing iterable
li = ['Manjeet', '19', '411997']

# initializing dict
di = {'name': "Nikhil", 'age': 19, 'DOB': '1391997'}

# using _asdict() to return an OrderedDict()
print("The OrderedDict instance using namedtuple is  : ")
print(S._asdict())

Output
The OrderedDict instance using namedtuple is  : 
OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])

Using “**” (double star) operator

This function is used to convert a dictionary into the namedtuple(). In this example, we are using “**” to convert the input list into namedtuple.

Python3
import collections

# Declaring namedtuple()
Student = collections.namedtuple('Student',
                                 ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# initializing iterable
li = ['Manjeet', '19', '411997']

# initializing dict
di = {'name': "Nikhil", 'age': 19, 'DOB': '1391997'}

# using ** operator to return namedtuple from dictionary
print("The namedtuple instance from dict is  : ")
print(Student(**di))

Output
The namedtuple instance from dict is  : 
Student(name='Nikhil', age=19, DOB='1391997')

Additional Operations 

There are some additional operations that are provided in Python for NamedTuples:

  • _fields
  • _replace()
  • __new__()
  • __getnewargs__()

_fields

This data attribute is used to get all the keynames of the namespace declared. In this example, we are using _fields to get all the keynames of the namespace declared.

Python3
import collections
Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# using _fields to display all the keynames of namedtuple()
print("All the fields of students are : ")
print(S._fields)

Output
All the fields of students are : 
('name', 'age', 'DOB')

_replace()

_replace() is like str.replace() but targets named fields( does not modify the original values). In this example, we are using _replace() to replace a name from “Nandini” to “Manjeet”.

Python3
import collections

# Declaring namedtuple()
Student = collections.namedtuple('Student', 
                           ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# ._replace returns a new namedtuple, 
# it does not modify the original
print("returns a new namedtuple : ")
print(S._replace(name='Manjeet'))

Output
returns a new namedtuple : 
Student(name='Manjeet', age='19', DOB='2541997')

__new__()

This function returns a new instance of the Student class, by taking the values that we want to assign to the keys in the named tuple. In this example, we are using __new__() to return a new instance of the Student class.

Python3
import collections

# Declaring namedtuple()
Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

# Student.__new__ returns a new instance of Student(name,age,DOB)
print(Student.__new__(Student,'Himesh','19','26082003'))

Output
Student(name='Himesh', age='19', DOB='26082003')

__getnewargs__()

This function returns the named tuple as a plain tuple. In this example, we are doing the same by using __getnewargs__().

Python3
import collections

# Declaring namedtuple()
Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])

# Adding values
S = Student('Nandini', '19', '2541997')

H=Student('Himesh','19','26082003')
# .__getnewargs__ returns the named tuple as a plain tuple
print(H.__getnewargs__())

Output
('Himesh', '19', '26082003')


Previous Article
Next Article

Similar Reads

How to use NamedTuple and Dataclass in Python?
We have all worked with classes and objects for more than once while coding. But have you ever wondered how to create a class other than the naive methods we have all been taught. Don't worry in this article we are going to cover these alternate methods. There are two alternative ways to construct a class in Python. NamedTuple DataClass First, of a
2 min read
Difference between DataClass vs NamedTuple vs Object in Python
Data Class: Data Class is a type of class that is used to store data without any functionality. These data classes are just regular classes having the main purpose to store state and data without knowing the constraints and logic behind it. Whenever you create a class that mostly contains attributes and certain properties to deal with the data and
3 min read
typing.NamedTuple – Improved Namedtuples
The NamedTuple class of the typing module added in Python 3.6 is the younger sibling of the namedtuple class in the collections module. The main difference being an updated syntax for defining new record types and added support for type hints. Like dictionaries, NamedTuples contain keys that are hashed to a particular value. But on the contrary, it
2 min read
Important differences between Python 2.x and Python 3.x with examples
In this article, we will see some important differences between Python 2.x and Python 3.x with the help of some examples. Differences between Python 2.x and Python 3.x Here, we will see the differences in the following libraries and modules: Division operatorprint functionUnicodexrangeError Handling_future_ modulePython Division operatorIf we are p
5 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Python | Merge Python key values to list
Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let's discuss certain ways in which this problem can be solved.
4 min read
Reading Python File-Like Objects from C | Python
Writing C extension code that consumes data from any Python file-like object (e.g., normal files, StringIO objects, etc.). read() method has to be repeatedly invoke to consume data on a file-like object and take steps to properly decode the resulting data. Given below is a C extension function that merely consumes all of the data on a file-like obj
3 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', level = logging.ERROR) # Variables (to make the calls that follo
2 min read
Python | Add Logging to Python Libraries
In this article, we will learn how to add a logging capability to a library, but don’t want it to interfere with programs that don’t use logging. For libraries that want to perform logging, create a dedicated logger object, and initially configure it as shown in the code below - Code #1 : C/C++ Code # abc.py import logging log = logging.getLogger(_
2 min read
JavaScript vs Python : Can Python Overtop JavaScript by 2020?
This is the Clash of the Titans!! And no...I am not talking about the Hollywood movie (don’t bother watching it...it's horrible!). I am talking about JavaScript and Python, two of the most popular programming languages in existence today. JavaScript is currently the most commonly used programming language (and has been for quite some time!) but now
5 min read
three90RightbarBannerImg