sorted() function accepts a key function as an argument and calls it on each element prior to make comparison with other elements.
list_of_dict = [{'ename': 'John', 'salary': 10000}, {'ename': 'Danny', 'salary': 60000}, {'ename': 'John', 'salary': 40000}, {'ename': 'Hanny', 'salary': 30000}, {'ename': 'Korra', 'salary': 50000}, {'ename': 'Aung', 'salary': 40000}, {'ename': 'Marry', 'salary': 60000}] print(list_of_dict) print('Sort by salary(Descending)') print(sorted(list_of_dict, key=lambda x: x['salary'], reverse=True)) print('Sort by Ename(Ascending)') print(sorted(list_of_dict, key=lambda x: x['ename'])) print('Sort by ename and salary(Ascending)') print(sorted(list_of_dict, key=lambda x: (x['ename'], x['salary'])))
Itemgetter can be used instead of lambda function to achieve the similar functionality. Itemgetter Outputs in the same way as sorted() and lambda does, but has different internal implementation. It takes keys of dictionaries and converts them into tuples. It reduces overhead and is faster and more efficient.
from operator import itemgetter print('Using itemgetter:') print('Sort by salary(Descending)') print(sorted(list_of_dict, key=itemgetter('salary'), reverse=True)) print('Sort by Ename(Ascending)') print(sorted(list_of_dict, key=itemgetter('ename'))) print('Sort by ename and salary(Ascending)') print(sorted(list_of_dict, key=itemgetter('ename', 'salary')))
This article is contributed by Prakash. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.