How do I sort a list of dictionaries by values of the dictionary in Python?

PythonServer Side ProgrammingProgramming

Python has a built-in function sorted() which sorts elements of an iterable in a given order.

sorted(iterable[, key][, reverse]

Second parameter is a function whose return value is used as key for sorting. Third parameter is by default false, if true the sorted list appears in descending order.

We use a lambda function which defines value of a dictionary key as key for sorted function. Following example sorts a list of dictionaries according to ascending order of value associated to key.

>>> dictlist=[{'name':'Rahul', 'age':23, 'marks':60}, {'name':'Anil', 'age':18, 'marks':55}, {'name':'Sunil', 'age':21, 'marks':90}]
>>> newlist=sorted(dictlist, key = lambda k:k['name'])
>>> newlist
[{'name': 'Anil', 'age': 18, 'marks': 55}, {'name': 'Rahul', 'age': 23, 'marks': 60}, {'name': 'Sunil', 'age': 21, 'marks': 90}]
>>> newlist=sorted(dictlist, key = lambda k:k['age'])
>>> newlist
[{'name': 'Anil', 'age': 18, 'marks': 55}, {'name': 'Sunil', 'age': 21, 'marks': 90}, {'name': 'Rahul', 'age': 23, 'marks': 60}]
>>> newlist=sorted(dictlist, key = lambda k:k['marks'], reverse=True)
>>> newlist
[{'name': 'Sunil', 'age': 21, 'marks': 90}, {'name': 'Rahul', 'age': 23, 'marks': 60}, {'name': 'Anil', 'age': 18, 'marks': 55}]
Published on 11-Jan-2018 23:57:24