[Tutor] Re: sorting a list of dictionaries

Andrei project5 at redrival.net
Wed Apr 13 08:13:39 CEST 2005


Gooch, John <John.Gooch <at> echostar.com> writes:

> 	lst.sort(lambda m, n: cmp(m.get(field), n.get(field)))
> 	where field is either 'name' or 'size'.
> What is "n:" and what is "lambda m" ? 

You could rewrite that in a more readable manner as follows:


def comparedict(dict1, dict2):
    "Compares the values of a certain key in the two dictionaries."
    item1 = dict1[field]
    item2 = dict2[field]
    return cmp(item1, item2)

lst.sort(comparedict)


m and n then correspond to dict1/dict2 (function arguments), lambda is in this
context just a different way of defining a function. The net result is a
comparison function which is called by the sort() method in order to determine
which of two dictionaries is 'smaller' or 'larger'.

Yours,

Andrei




More information about the Tutor mailing list