Sort list of dictionaries

Chris Angelico rosuav at gmail.com
Tue Mar 3 11:09:01 EST 2015


On Wed, Mar 4, 2015 at 2:56 AM, Charles Heizer <ceh329 at gmail.com> 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.



More information about the Python-list mailing list