Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+3 votes
5 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

2 Answers

0 votes
by (46k 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 (106k points)
edited by

import operator

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

list_of_dicts.sort(key=operator.itemgetter('name'))

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

list_of_dicts.sort(key=operator.itemgetter('age'))

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

Learn in detail about Python by enrolling in Intellipaat Python Course online and upskill.

Related questions

0 votes
2 answers
asked Aug 23, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 2, 2019 in Python by Sammy (47.6k points)
+1 vote
1 answer

Browse Categories

...