Search⌘ K

Modules in Python: namedtuple

Explore how namedtuple in Python’s collections module allows you to create tuple subclasses with named fields. Understand creating namedtuples, accessing items by name instead of index, and converting dictionaries into namedtuple objects. Learn about useful arguments like verbose and rename to customize namedtuple behavior, enhancing how you manage grouped data.

Overview of namedtuple

Let’s discuss the namedtuple class from the collection module which we can use to replace Python’s tuple. Of course, the namedtuple is not a drop-in replacement as we will see soon. We have seen some programmers use it like a struct. If we haven’t used a language with a struct in it, then that needs a little explanation. A struct is basically a complex data type that groups a list of variables under one name.

Creating namedtuple

Let’s look at an example of how to create a namedtuple so we can see how they work:

Python 3.5
from collections import namedtuple
Parts = namedtuple("Parts", "id_num desc cost amount")
auto_parts = Parts(id_num="1234", desc="Ford Engine", cost=1200.00, amount=10)
print(auto_parts.id_num)

Here we import namedtuple from the ...