Narly NamedTuples in Python

This article was first published on Python – Hutsons-hacks , and kindly contributed to python-bloggers. (You can report issue about the content on this page here)
Want to share your content on python-bloggers? click here.


Fork


Star


Watch


Download


Issue

NamedTuples are an excellent way to make your Python code more useful and readable. In short a NamedTuple is an alternative to the built-in tuple . This extension type enhances standard tuples so that their elements can be accessed by both their attribute name and the positional index.

This is really powerful, as you can then refer to fields by their name or positional index, much like you can with a Pandas DataFrame.

Where to get the code?

The code for this tutorial is available from this link: https://github.com/StatsGary/PyHacks-Tutorials/blob/main/27_namedtuples.py.

Creating a standard list, for comparison

Firstly we will create a standard list of rockers with a rocker name and a band attribute:

We will then create a loop the standard way to print out the results:

Here to get the name attribute the only way we can do this with a standard list is to use the positional index of the list. As you can see in the loop code above we take the zeroth index as the first item, and the band would be in index 1. This is the limitation of standard lists.

This outputs this to the console:

Introducing the power of the NamedTuple

This is where we start to use the namedtuple. Firstly, we need to import this from the collections package:

Implementing the namedtuple

Firstly, we need to implement the structure of the named tuple:

Here I create a namedtuple with the name Rockers and then pass in the attribute names, as I only have band and rocker name, these are the two that I will store.

Create the list with the namedtuple wrapper

Next, I will create a similar list, but this time I will create internal tuples with the variable name I defined it. In this case it will be Rockers as that is what I called my variable for the namedtuple, but it could be anything that is relevant to your use case. The namedtuple implementation is here:

You can see this follows the structure of the namedtuple we defined.

Looping through the list and accessing the elements by name

As stated at the start of this blog. The benefits of the namedtuple are that it gives you the flexibility to refer to items by their name or associated index. Here we will loop through the namedtuple and grab the rocker_name and the band. We will then print these out to the console, but essentially then you could do other manipulations on the tuple:

This has given us the added flexibility of referring to the attribute names, as opposed to trying to grab a positional index. The result of this is below:

Suppose I want to change the value of Dave Grohl’s band to Nirvana, as technically he has been in both bands, then the following is how we would achieve this.

Change value in namedtuple

Here I will grab Dave Grohl at index 0 and then replace one of the tuple elements band from Foo Fighters to Nirvana:

From the print statement you can see that this value has been changed:

Other things you can do

There are two other use cases I want to present with namedtuples, these are converting an existing list into a namedtuple and converting an existing dictionary to a namedtuple.

Convert list to a namedtuple

The way to do this is pretty straightforward. Say you have an existing list that has the same structure, below is how you would achieve this:

Using the ._make command we can see that the list has been turned into a namedtuple:

Viola – that’s how you do it!

Convert dictionary into namedtuple

The process is very similar to the above, but we will be undertaking unpacking of the dictionary into the namedtuple. This is how you do it:

We used the unpacking operator to pass multiple kwargs from the dictionary to the named tuple, these kwargs become the namedtuple attributes and values. We get the output below by printing:

Now go for a lie down and I will catch you again:

Gracioso big bang theory GIF - Find on GIFER
To leave a comment for the author, please follow the link and comment on their blog: Python – Hutsons-hacks .

Want to share your content on python-bloggers? click here.