How to sort list of dictionary by value python

Introduction #

Consider we have a Python list that contains 3 dictionaries:

[{'name':'John', 'age':20}, {'name':'Bob', 'age':15}, {'name':'Charles', 'age':30}]

When sorted by name, should become:

[{'name':'Bob', 'age':15}, {'name':'Charles', 'age':30}, {'name':'John', 'age':20}]

Using sorted funciton with lambda #

original_list = [{
    'name': 'John',
    'age': 20
}, {
    'name': 'Bob',
    'age': 15
}, {
    'name': 'Charles',
    'age': 30
}]

newlist = sorted(original_list, key=lambda k: k['name'])
print(newlist)

Output:

[{'name': 'Bob', 'age': 15}, {'name': 'Charles', 'age': 30}, {'name': 'John', 'age': 20}]

If sort using age:

newlist = sorted(original_list, key=lambda k: k['age'])
print(newlist)

Out:

[{'name': 'Bob', 'age': 15}, {'name': 'John', 'age': 20}, {'name': 'Charles', 'age': 30}]

Add reverse=True to sort descending

newlist = sorted(original_list, key=lambda k: k['name'], reverse=True)
print(newlist)

Out:

[{'name': 'John', 'age': 20}, {'name': 'Charles', 'age': 30}, {'name': 'Bob', 'age': 15}]

Using operator module #

import operator
print('Before sorting:')
print(original_list)
original_list.sort(key=operator.itemgetter('name'))
print('After sorting:')
print(original_list)

Out:

Before sorting:
[{'name': 'John', 'age': 20}, {'name': 'Bob', 'age': 15}, {'name': 'Charles', 'age': 30}]
After sorting:
[{'name': 'Bob', 'age': 15}, {'name': 'Charles', 'age': 30}, {'name': 'John', 'age': 20}]

Completed example code #

original_list = [{
    'name': 'John',
    'age': 20
}, {
    'name': 'Bob',
    'age': 15
}, {
    'name': 'Charles',
    'age': 30
}]

newlist = sorted(original_list, key=lambda k: k['name'])

print(newlist)

newlist = sorted(original_list, key=lambda k: k['age'])

print(newlist)

newlist = sorted(original_list, key=lambda k: k['name'], reverse=True)
print(newlist)

import operator
print('Before sorting:')
print(original_list)
original_list.sort(key=operator.itemgetter('name'))
print('After sorting:')
print(original_list)

Tags:

Python