• Post author:
  • Post category:Python
  • Reading time:2 mins read

Here is a Python program to sort a list of dictionaries in Python by a key.

Sort List of Dictionaries in Python by a Key

The following Python program will sort the list of directories by key first_name, last_name and on user_id.

rows = [
    {'first_name': 'Brian', 'last_name': 'Jones', 'user_id': 10003},
    {'first_name': 'David', 'last_name': 'Beazley', 'user_id': 10002},
    {'first_name': 'John', 'last_name': 'Cleese', 'user_id': 10001},
    {'first_name': 'Big', 'last_name': 'Jones', 'user_id': 10004}
]

from operator import itemgetter

rows_by_first_name = sorted(rows, key=itemgetter('first_name'))
rows_by_user_id = sorted(rows, key=itemgetter('user_id'))

from pprint import pprint

print("Sorted by first_name:")
pprint(rows_by_first_name)

print("Sorted by user_id:")
pprint(rows_by_user_id)

rows_by_lfirst_name = sorted(rows, key=itemgetter('last_name','first_name'))
print("Sorted by last_name,first_name:")
pprint(rows_by_lfirst_name)

Output:

Sorted by first_name:
[{'first_name': 'Big', 'last_name': 'Jones', 'user_id': 10004},
{'first_name': 'Brian', 'last_name': 'Jones', 'user_id': 10003},
{'first_name': 'David', 'last_name': 'Beazley', 'user_id': 10002},
{'first_name': 'John', 'last_name': 'Cleese', 'user_id': 10001}]
Sorted by user_id:
[{'first_name': 'John', 'last_name': 'Cleese', 'user_id': 10001},
{'first_name': 'David', 'last_name': 'Beazley', 'user_id': 10002},
{'first_name': 'Brian', 'last_name': 'Jones', 'user_id': 10003},
{'first_name': 'Big', 'last_name': 'Jones', 'user_id': 10004}]
Sorted by last_name,first_name:
[{'first_name': 'David', 'last_name': 'Beazley', 'user_id': 10002},
{'first_name': 'John', 'last_name': 'Cleese', 'user_id': 10001},
{'first_name': 'Big', 'last_name': 'Jones', 'user_id': 10004},
{'first_name': 'Brian', 'last_name': 'Jones', 'user_id': 10003}]

Process finished with exit code 0

See also:

Vinish Kapoor

An Oracle Apex Consultant, Oracle ACE, and founder of foxinfotech.in and orclqa.com a question and answer forum for developers.