+3 votes
2 views
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

1 Answer

0 votes
by (21.4k 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.

...