Python

Python Namedtuple

Python comes up with many built-in data structures like lists, dictionaries, and tuples to store and manage the data efficiently. The namedtuple is the dictionary-like container available in the “collections” module. Similar to the dictionaries, the namedtuple also contains the keys that are mapped to values. However, the namedtuple allows accessing the values through keys and as well as through indexes. As compared to the Python dictionaries, accessing the values through indexes is the additional functionality in namedtuple. This article explains the Python namedtuple in detail with examples.

Accessing values from the namedtuple

The values inside the namedtuple can be accessed in the following ways:

  1. By using the keys
  2. By using the indexes
  3. By using the getattr() function

As the namedtuple converts the field into the attributes, therefore it is easy to access the values using the getattr() function.

Examples

Now let’s see some examples to understand the creation and working of namedtuple. To create and use the namedtuple, first, we need to import the collections module. In the below given an example, a namedtuple for a teacher is created. The keys of the namedtuple are name, age, and department, respectively. The values are accessed using indexes and keys.

#importing the collections module

import collections

#creating a namedtuple for a teacher

#name, age, and department are the keys

Teacher= collections.namedtuple('Teacher',['name','age','department'])

# create a new teacher and adding the values

teacher_john = Teacher("John",29,"Computer Science")

#accessing the teacher values using indexes

print("Accessing values using indexes:")

print("Teacher name is:",teacher_john[0])

print("Teacher age is:",teacher_john[1])

print("Teacher department is:",teacher_john[2])

#accessing the teacher values using keys

print("Accessing values using keys:")

print("Teacher name is:",teacher_john.name)

print("Teacher age is:",teacher_john.age)

print("Teacher department is:",teacher_john.department)

Output

Now let’s access the values using the getattr() function. The namedtuple and the key is passed as an argument to the getattr() function.

#importing the collections module

import collections

#creating a namedtuple for a teacher

#name, age, and department are the keys

Teacher= collections.namedtuple('Teacher',['name','age','department'])

# create a new teacher and adding the values

teacher_john = Teacher("John",29,"Computer Science")

#accessing the teacher values using the getattr() function

print(getattr(teacher_john,"name"))

print(getattr(teacher_john,"age"))

print(getattr(teacher_john,"department"))

Output

Popular operations of namedtuple

Some popular functions convert the other collections like lists, dictionaries, and tuples into namedtuple and return the namedtuple information. Following are the functions that convert the other collections to namedtuple:-

  • _make()
  • _asdict()
  • ** operator

The _make() function converts an iterable object like list and tuple into a namedtuple. The _asdict() function makes an orderDict from the namedtuple and returns it. Lastly, the ** operator converts a dictionary into a namedtuple. Additionally, the functions that return the namedtuple information are the following:

  • _fields
  • _replace()

The _fields() function returns all the fields of the namedtuple whereas, the _replace() function replaces a particular value with another value.

Let’s implement the functions as mentioned above in our Python script to convert the different collections into namedtuple.

#importing the collections module

import collections

#creating a namedtuple for a teacher

#name, age, and department are the keys

Teacher= collections.namedtuple('Teacher',['name','age','department'])

# create a new teacher and adding the values

teacher_john = Teacher("John",29,"Computer Science")

#creating a list

teacher_list =["Mark",30,"Business Administration"]

#creating a dictionary

teacher_dict ={'name':'Talor','age': 32,'department':'Economics'}

#using _make() function to convert list to namedtuple

print ("List to namedtuple conversion : ")

print(Teacher._make(teacher_list))

#using _asdict() function to make an OrderDict

print ("Making the OrderedDict: ")

print(teacher_john._asdict())

#using the ** to convert a dictionary into a namedtuple

print ("Converting the dictionary into namedtuple: ")

print(Teacher(**teacher_dict))

Output

Now let’s use the _fields(), and _replace() functions to get the keys’ information and replace the keys, respectively.

#importing the collections module

import collections

#creating a namedtuple for a teacher

#name, age, and department are the keys

Teacher= collections.namedtuple('Teacher',['name','age','department'])

# create a new teacher and adding the values

teacher_john = Teacher("John",29,"Computer Science")

#using _fields function to get the keys of namedtuple

print("The keys of namedtuple are:")

print(Teacher._fields)

#using _replace function to replace the value

print("The replace value of name is:")

print(teacher_john._replace(name = 'Donald'))

Output
In the output, it can be seen that the _fields function returns the keys of information, and the _replace() function replaces the name successfully.

Conclusion

The namedtuple is the dictionary-like container present in the “collections” module. It contains the key and maps the values to the key. Unlike the Python dictionary, the namedtuples values can also be accessed using the indexes and getattr() function. This article briefly explains the namedtuple through examples.

About the author

Kamran Sattar Awaisi

Kamran Sattar Awaisi

I am a software engineer and a research scholar. I like to write article and make tutorial on various IT topics including Python, Cloud Computing, Fog Computing and Deep Learning. I love to use Linux based operating systems.