Python sort array of dictionaries by value in the dictionary

By: Varghese Chacko 1 year, 2 months ago

One of the cases we face in programming is sorting an array of dictionaries by value in the dictionary. In Python, it is possible to write a one-liner to achive the same. Suppose we have a list of dictwith name and age of students in a class.

students = [
    {"name": "k", "age":11 },
    {"name": "a", "age":6 },
    {"name": "w", "age":1 },
    {"name": "t", "age":4 },
    {"name": "y", "age":5 },
    {"name": "r", "age":2 },
    {"name": "q", "age":0 },
    {"name": "i", "age":10 },
    {"name": "s", "age":7 },
    {"name": "d", "age":8 },
    {"name": "e", "age":3 },
    {"name": "f", "age":9 },
]

To sort the array in order by name

>>> def sort_by_name(d):
...     return d.get('name')
... 
>>> sorted(students, key=sort_by_name)
[
    {'age': 6, 'name': 'a'}, 
    {'age': 8, 'name': 'd'}, 
    {'age': 3, 'name': 'e'}, 
    {'age': 9, 'name': 'f'}, 
    {'age': 10, 'name': 'i'}, 
    {'age': 11, 'name': 'k'}, 
    {'age': 0, 'name': 'q'}, 
    {'age': 2, 'name': 'r'}, 
    {'age': 7, 'name': 's'}, 
    {'age': 4, 'name': 't'}, 
    {'age': 1, 'name': 'w'}, 
    {'age': 5, 'name': 'y'}
]
>>> 

The sorted method passes each item in the list to the key method sort_by_name and the key method returns the value of the key name, hence the dictionary is sorted by name. To sort by age, we can write a method to return age from the dictionary. This looks very simple function. wecan replace it with a lambda as follows

>>> sorted(students, key=lambda d: d.get('age'))
[
    {'age': 0, 'name': 'q'}, 
    {'age': 1, 'name': 'w'}, 
    {'age': 2, 'name': 'r'}, 
    {'age': 3, 'name': 'e'}, 
    {'age': 4, 'name': 't'}, 
    {'age': 5, 'name': 'y'}, 
    {'age': 6, 'name': 'a'}, 
    {'age': 7, 'name': 's'}, 
    {'age': 8, 'name': 'd'}, 
    {'age': 9, 'name': 'f'}, 
    {'age': 10, 'name': 'i'}, 
    {'age': 11, 'name': 'k'}
]
>>> 

Above example with lambda, I am sorting the list by age.

Python's operator package provides a method itemgetter, which returns a callable object that returns an item from operand. We can use itemgetter askey method. 

>>> from operator import itemgetter
>>> sorted(students, key=itemgetter('age'))
[
    {'age': 0, 'name': 'q'}, 
    {'age': 1, 'name': 'w'}, 
    {'age': 2, 'name': 'r'}, 
    {'age': 3, 'name': 'e'}, 
    {'age': 4, 'name': 't'}, 
    {'age': 5, 'name': 'y'}, 
    {'age': 6, 'name': 'a'}, 
    {'age': 7, 'name': 's'}, 
    {'age': 8, 'name': 'd'}, 
    {'age': 9, 'name': 'f'}, 
    {'age': 10, 'name': 'i'}, 
    {'age': 11, 'name': 'k'}
]
>>> 

We can do  literally anything to key method and sort them.