0

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.

3

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.