# How to Sort a List of Dictionaries by a key in Python

## Problem –

You have a list of dictionaries and you want to sort it based on a key in the dictionary.

## Solution –

Let’s say we have a list of dictionary of stock prices and we want to sort it by stock name or price or may be both.

``````In [1]: prices = [{'name':'icici','price':712},
...:         {'name':'itc','price':245},
...:         {'name':'reliance','price':2463},
...:         {'name':'airtel','price':707}]``````

The sorting can be easily done using operator module’s itemgetter function.

``````In [2]: from operator import itemgetter

In [3]: by_price = sorted(prices, key=itemgetter('price'))

In [4]: by_price
Out[4]:
[{'name': 'itc', 'price': 245},
{'name': 'airtel', 'price': 707},
{'name': 'icici', 'price': 712},
{'name': 'reliance', 'price': 2463}]

In [5]: by_name = sorted(prices, key=itemgetter('name'))

In [6]: by_name
Out[6]:
[{'name': 'airtel', 'price': 707},
{'name': 'icici', 'price': 712},
{'name': 'itc', 'price': 245},
{'name': 'reliance', 'price': 2463}]``````

You can also sort by multiple keys.

``````In [7]: by_name_price = sorted(prices, key=itemgetter('name','price'))

In [8]: by_name_price
Out[8]:
[{'name': 'airtel', 'price': 707},
{'name': 'icici', 'price': 712},
{'name': 'itc', 'price': 245},
{'name': 'reliance', 'price': 2463}]``````

Rating: 1 out of 5.