Question

Is it possible to create a tuple in Python with indices that are string-based, not number based? That is, if I have a tuple of ("yellow", "fish", "10), I would be able to access by [color] instead of [0]. This is really only for the sake of convenience.

Was it helpful?

Solution

You can use collections.namedtuple():

>>> from collections import namedtuple
>>> MyObject = namedtuple('MyObject', 'color number')
>>> my_obj = MyObject(color="yellow", number=10)
>>> my_obj.color
'yellow'
>>> my_obj.number
10

And you can still access items by index:

>>> my_obj[0]
'yellow'
>>> my_obj[1]
10

OTHER TIPS

Yes, collections.namedtuple does this, although you'll access the color with x.color rather than x['color']

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top