Example 1-
[{‘name’:’Homer’, ‘age’:39}, {‘name’:’Bart’, ‘age’:10}]
Output should be:
[{‘name’:’Bart’, ‘age’:10}, {‘name’:’Homer’, ‘age’:39}]

Solution-
(i) newlist = sorted(list_to_be_sorted, key=lambda k: k[‘name’])
(ii) from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter(‘name’))

Example 2-
myDict = { ‘item1’ : [ 7, 1, 9], ‘item2’ : [8, 2, 3], ‘item3’ : [ 9, 3, 11 ] }
Sorting based on 3nd element of list

Solution-
sorted(myDict.items(), key=lambda e: e[1][2])

Advertisements