Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: can I have a list with named indices?

Tags:

python

arrays

In PHP I can name my array indices so that I may have something like:

$shows = Array(0 => Array('id' => 1, 'name' => 'Sesame Street'),                 1 => Array('id' => 2, 'name' => 'Dora The Explorer')); 

Is this possible in Python?

like image 820
UnkwnTech Avatar asked Oct 07 '08 12:10

UnkwnTech


2 Answers

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.

like image 111
Michael Twomey Avatar answered Oct 05 '22 15:10

Michael Twomey


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'} 
like image 33
Deestan Avatar answered Oct 05 '22 15:10

Deestan