JS Problems geeksforgeeks Exercises and Solutions for Beginners

How to Sort a List of Dictionaries By Field in Python [All Method]️

It’s also a question How to Sort a List of Dictionaries By Field in Python? If you get stuck or have questions at any point,simply comment below.
Question: What is the best way to approach this problem? Answer: Check out this blog code to learn how to fix errors How to Sort a List of Dictionaries By Field in Python. Question:”What should you do if you run into code errors?” Answer:”By following this blog, you can find a solution.”

Suppose we have a list of dictionaries in Python.

lst = [
    {'id': 2, 'dog': 'corgi'},
    {'id': 5, 'dog': 'shih tzu'},
    {'id': 3, 'dog': 'pug'}
]

We want to sort this list of dictionaries by the key id.

sorted() with lambda

We can use the sorted() function’s key parameter to do this.

sorted_lst = sorted(lst, key=lambda k: k['id'])

sorted() with itemgetter

Instead of using a lambda function, we can use itemgetter to identify the key to sort by.

from operator import itemgetter
sorted_lst = sorted(lst, key=itemgetter('id'))

This can slightly simplify our code, but it functions exactly the same.

Sort in Descending Order

Finally, we can sort in descending order using the sorted() function’s reverse parameter.

sorted_lst = sorted(lst, key=lambda k: k['id'], reverse=True)
from operator import itemgetter
sorted_lst = sorted(lst, key=itemgetter('id'), reverse=True)


Now you learned, How you can use & How to Sort a List of Dictionaries By Field in Python.
If you need help at any point, please send me a message and I will do my best to assist you.

Related Articles

Leave a Reply

Your email address will not be published.

Back to top button