Newbie: sort list of dictionaries

Paul Rubin http
Tue Dec 30 13:41:11 CET 2003


Sven Brandt <no_more_spam at no_use_for.me> writes:
> I have a list of dictionaries. I want the elements of the list to be
> sorted by the value of a key of the dict .
> 
> Excample:
> my_list=[{'title': 'foo', 'id': 5, 'text': 'some text'},
>           {'title': 'bar', 'id': 3, 'text': 'my text'},
>           {'title': 'bla', 'id': 6, 'text': 'any text'}, ]
> 
> my_list.sort("by the id value")

The Pythonic way to do it may not be what you're used to, but once you
understand it you'll be able to apply the understanding to other areas
of programming.

The list sort method lets you pass an optional comparison function,
that takes two items and returns -1, 0, or 1, depending on what order
the items are supposed to appear in.  The comparison function takes
exactly two args (the items to be compared).  You can't pass a third
arg to specify the field name.  You could do something ugly like use a
global variable, but the preferred way given a field name is to
construct a brand new comparison function just for that name:

    def compare_by (fieldname):
       def compare_two_dicts (a, b):
          return cmp(a[fieldname], b[fieldname])
       return compare_two_dicts

What's that?  Two nested function definitions.  The outer function,
compare_by, creates a new function called compare_two_dicts, which
compares specifically based on the field that you passed to the outer
function.  compare_by then returns the new function, that's right,
functions are values in Python!  You can then can pass the new
function to the sort method:

   my_list.sort (compare_by ('id'))

And my_list is then properly sorted:

[{'text': 'my text', 'id': 3, 'title': 'bar'},
 {'text': 'some text', 'id': 5, 'title': 'foo'},
 {'text': 'any text', 'id': 6, 'title': 'bla'}]




More information about the Python-list mailing list