Sorting dictionary of list


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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s