Sort list of dictionaries

Paul Moore p.f.moore at gmail.com
Tue Mar 3 11:48:38 EST 2015


On Tuesday, 3 March 2015 16:09:31 UTC, Chris Angelico  wrote:
> On Wed, Mar 4, 2015 at 2:56 AM, Charles Heizer wrote:
> >> Personally, I prefer to not use a lambda:
> >>
> >> def name_version(elem):
> >>     return elem['name'], LooseVersion(elem['version'])
> >>
> >> result = sorted(mylist, key=name_version, reverse=True)
> >
> > Peter, thank you. Me being new to Python why don't you prefer to use a lambda?
> 
> Using lambda is fine if it's really clear what's going on (usually, if
> it's an extremely simple function), but if your expression goes across
> multiple lines because of the function parameter, it's usually simpler
> to break the function out into a separate def statement and then use
> that. There's ultimately no difference[1] between a lambda function
> and a def function, apart from the fact that a function created with
> lambda always has the name "<lambda>".
> 
> ChrisA
> 
> [1] Modulo bugs, eg a weird edge case with lambda and yield; certainly
> no intentional difference.

The main point is that a def gives your function a name, whereas lambda is unnamed. It sometimes feels harder to have to think of a name for something that seems simple, like your key function. But when you come back to it in a few months, the name is incredibly useful documentation as to what's going on.

Paul



More information about the Python-list mailing list