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.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
goodcow
  • 4,495
  • 6
  • 33
  • 52
  • You might want to look into using a dictionary instead http://www.tutorialspoint.com/python/python_dictionary.htm or Enums can be another option but they were only introduced in later versions of python http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python – user1135469 May 10 '14 at 02:52
  • 1
    Why not a dictionary? – thefourtheye May 10 '14 at 02:52
  • 2
    [`namedtuple`](https://docs.python.org/2/library/collections.html#collections.namedtuple) – devnull May 10 '14 at 02:55

2 Answers2

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
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
0

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

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118