+3 votes
in Python by (1.2k points)
edited by

I want each item to be sorted by a specific property value from a list of dictionaries I have.

Take the following array into consideration:

[{'name':'Robb', 'age':28}, {'name':'Robert', 'age':14}]

It should become,

[{'name':'Robert', 'age':14}, {'name':'Rob', 'age':28}]

When sorted by name

2 Answers

0 votes
by (32.7k points)
edited by

Instead of using cmp use a key it will make it look cleaner

Newlist=sorted(list_to_be_sorted, key=lambadak: k[‘name’]

Or you can also use

fromoperator import itemgetter

newlist=sorted(list_to_besorted, key=itemgetter(‘name’))

For completeness just add reverse=true to sort descending

Newlist=sorted(1, key=itemgetter(‘name’), reverse=True)

Make sure to write every command carefully. Happy Learning.

0 votes
by (65.9k points)

import operator

To sort the list of dictionaries by key='name':


To sort the list of dictionaries by key='age':


You can use the following video tutorials to clear all your doubts:-