Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8400

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'109175', u'type': u'Created Section', 'class': 'addbold'} ,
{u'status': u'Active', u'name': u'G', u'orgID': u'109175', u'type': u'Created Section', 'class': 'addbold'} ,
{u'status': u'Active', u'name': u'D', u'orgID': u'109175', u'type': u'Created Section', 'class': 'addbold'}]

I want to arrange the list items in alphabetic order based on name key of dictionary.

So output would be like this,

[{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'}]

How can I sort list dict items in this list?

Upvotes: 2

Views: 192

Answers (1)

falsetru
falsetru

Reputation: 368904

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'))

Upvotes: 6

Related Questions