Sort List of Dictionary by Key in Python

Here is example code to perform sorting list of dictionary by dictionary key.
For example I need to sort my list by level.

from operator import itemgetter

tmp = [
    {'name': 'foo', 'age': 35, 'level': 1},
    {'name': 'bar', 'age': 11, 'level': 5},
    {'name': 'john', 'age': 28, 'level': 3},
    {'name': 'doe', 'age': 74, 'level': 9},
    {'name': 'alex', 'age': 12, 'level': 7},
]

print sorted(tmp, key=itemgetter('level'))                # Sort ascending
print sorted(tmp, key=itemgetter('level'), reverse=True)  # Sort descending

Reference: https://wiki.python.org/moin/SortingListsOfDictionaries

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s