Skip to content Skip to sidebar Skip to footer

Sort Dictionary Elements In List

For this list, [{u'status': u'Active', u'name': u'X', u'orgID': u'109175', u'type': u'Created Section','class': 'addbold'} , {u'status': u'Active', u'name': u'A', u'orgID': u'109

Solution 1:

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.

importoperator
sorted(lst, key=operator.itemgetter('name'))

Post a Comment for "Sort Dictionary Elements In List"