Newbie: sort list of dictionaries

Sven Brandt no_more_spam at
Tue Dec 30 14:05:22 CET 2003

Hi Paul,

thanks a lot, esp. for the good explanation. That's excactly what i needed.


Paul Rubin schrieb:
> 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:

More information about the Python-list mailing list