How to Sort a List of Dictionaries By Field in Python


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)