Python: can I have a list with named indices?

前端 未结 8 1556
天涯浪人
天涯浪人 2020-12-10 10:06

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

$shows = Array(0 => Array(\'id\' => 1, \'name\' => \'Sesame Street\'), 
               


        
相关标签:
8条回答
  • 2020-12-10 11:01

    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: 'Sesaeme Street', 2:'Dora the Explorer'}
    
    0 讨论(0)
  • 2020-12-10 11:01

    The pandas library has a really neat solution: Series.

    book = pandas.Series( ['Introduction to python', 'Someone', 359, 10],
       index=['Title', 'Author', 'Number of pages', 'Price'])
    print book['Author']
    

    For more information check it's documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html.

    0 讨论(0)
提交回复
热议问题