Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top