[Tutor] sorting a list of dictionaries

Sean Perry shaleh at speakeasy.net
Wed Apr 13 06:49:01 CEST 2005


Gooch, John wrote:
> I am working on a dictionary sorting problem just like the one in the email
> thread at the bottom of this message. My question about their solution is:
> In these lines:
> 	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" ? 
> 

#!/usr/bin/python 


lst = [{"foo": 6, "bar": 10}, {"foo": 1, "bar": 2}]
field = "foo"

sort_func = lambda m, n: cmp(m.get(field), n.get(field))

lst.sort(sort_func)

print sort_func(lst[0], lst[1])
print lst

lambda creates a nameless function.


More information about the Tutor mailing list