Python: can I have a list with named indices?

PHP arrays are actually maps, which is equivalent to dicts in Python.

Thus, this is the Python equivalent:

showlist = [{'id':1, 'name':'Sesaeme Street'}, {'id':2, 'name':'Dora the Explorer'}]

Sorting example:

from operator import attrgetter

showlist.sort(key=attrgetter('id'))

BUT! With the example you provided, a simpler datastructure would be better:

shows = {1: 'Sesame Street', 2:'Dora the Explorer'}

@Unkwntech,

What you want is available in the just-released Python 2.6 in the form of named tuples. They allow you to do this:

import collections
person = collections.namedtuple('Person', 'id name age')

me = person(id=1, age=1e15, name='Dan')
you = person(2, 'Somebody', 31.4159)

assert me.age == me[2]   # can access fields by either name or position

Yes,

a = {"id": 1, "name":"Sesame Street"}

This sounds like the PHP array using named indices is very similar to a python dict:

shows = [
  {"id": 1, "name": "Sesaeme Street"},
  {"id": 2, "name": "Dora The Explorer"},
]

See http://docs.python.org/tutorial/datastructures.html#dictionaries for more on this.

Tags:

Python

Arrays