Sort dictionary elements in list

前端 未结 1 1657
终归单人心
终归单人心 2021-01-21 15:14

For this list,

[{u\'status\': u\'Active\', u\'name\': u\'X\', u\'orgID\': u\'109175\', u\'type\': u\'Created Section\',\'class\': \'addbold\'} , 
{u\'status\':          


        
相关标签:
1条回答
  • 2021-01-21 15:54

    sorted or list.sort accept optional key function parameter. The return value of the function is used to compare elements order.

    >>> lst = [...]
    >>> sorted(lst, key=lambda x: x['name'])
    [{u'status': u'Active', u'type': u'Created Section', u'orgID': u'109175', u'name': u'A', 'class': 'addbold'},
     {u'status': u'Active', u'type': u'Created Section', u'orgID': u'109175', u'name': u'D', 'class': 'addbold'},
     {u'status': u'Active', u'type': u'Created Section', u'orgID': u'109175', u'name': u'G', 'class': 'addbold'},
     {u'status': u'Active', u'type': u'Created Section', u'orgID': u'109175', u'name': u'X', 'class': 'addbold'}]
    

    operator.itemgetter('name') can be used in place of the lambda function.

    import operator
    sorted(lst, key=operator.itemgetter('name'))
    
    0 讨论(0)
提交回复
热议问题