Python's namedtuple is Great

May 10, 2022

I don't use the namedtuple often in Python, but every time I do, I ask myself, "Why aren't I using this more often?" Today I ran into a case where it made total sense to use it.

I'm loading data from a database into a dictionary, so that I can later use this data to seed additional tables. To keep things nice and flat, I use a tuple as the key into the dictionary:

ModelKey = namedtuple('ModelKey', 'org role location offset')
model_data = {}
for x in models.DataModelEntry.objects.filter(data_model=themodel):
    key = ModelKey(, x.role, x.location, x.offset)
    model_data.setdefault(key, x.value)

Later, when I use this data, I can use the field names directly, without having to remember in which slot I stored what parameter:

to_create = []
for key, value in model_data.items():
    obj = models.Resource(, role=key.role, location=key.location,
                          offset=key.offset, value=value)

The first line in the loop is so much clearer than the following:

    obj = models.Resource(org=key[0], role=key[1], location=key[2], offset=key[3], value=value)

Using the field names also makes debugging easier for future you!

Add a Comment
Ignore this field:
Leave this blank:
Optional; will not be indexed
Ignore this field:
Both Markdown and a limited set of HTML tags are supported
Leave this empty: