You are not logged in Log in Join
You are here: Home » Members » ontoprise » List sorting with dictionary elements

Log in
Name

Password

 

List sorting with dictionary elements

Sorting lists of basic Python objects is generally pretty efficient. The sort method for lists takes an optional comparison function as an argument that can be used to change the sorting behavior. This is quite convenient, though it can really slow down your sorts. And how about sorting a list containing dictionaries, all with the same keys for the use with the <dtml-in> tag in Zope?

An alternative way to speed up sorts is to construct a list of tuples whose first element is a sort key that will sort properly using the default comparison, and whose second element is the original list element, which is the dictionary in our case.

Suppose, for example, you have a list of tuples that you want to sort by the "name" field of each tuple. The following function will do that.

def sortDictBy(list, key):
    nlist = map(lambda x, key=key: (x[key], x), list)
    nlist.sort()
    return map(lambda (key, x): x, nlist)

Here's an example use:

list = [{'name': 'Master', 'prename': 'Albrecht', 'ranking': 10.5}, {'name': 'Brandenburg', 'prename': 'Bernd', 'ranking': 5.0}, {'name': 'Poustka', 'prename': 'Anne', 'ranking': 20.3}]

list = sortDictBy(list, "ranking")

This could be used inside a Python Script e.g.

This How-To is abutted to Guido van Rossums "Sorting" (in "Python Performance Tips" - same with lists).