Sort list of dictionaries
Peter Otten
__peter__ at web.de
Tue Mar 3 12:44:51 EST 2015
Charles Heizer wrote:
> On Monday, March 2, 2015 at 11:23:37 AM UTC-8, Peter Otten wrote:
>> Charles Heizer wrote:
>>
>> > Never mind, the light bulb finally went off. :-\
>> >
>> > sortedlist = sorted(mylist , key=lambda elem: "%s %s" % ( elem['name'],
>> > (".".join([i.zfill(5) for i in elem['version'].split(".")])) ),
>> > reverse=True)
>>
>> This lightbulb will break with version numbers > 99999 ;)
>>
>> Here are two alternatives:
>>
>> result = sorted(
>> mylist,
>> key=lambda elem: (elem['name'], LooseVersion(elem['version'])),
>> reverse=True)
>>
>> result = sorted(
>> mylist,
>> key=lambda e: (e["name"], tuple(map(int, e["version"].split(".")))),
>> reverse=True)
>>
>>
>> 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?
I find
def name_version(elem):
return elem['name'], LooseVersion(elem['version'])
more readable than
lambda elem: (elem['name'], LooseVersion(elem['version']))
and I can understand what
>> result = sorted(mylist, key=name_version, reverse=True)
is supposed to do without grokking the implementation of name_version()
first. I can spot a potential bug -- are the names really supposed to occur
in reverse order, not just the versions? -- again without a look at the
implementation.
If I intend to use the script more than once or if I want to rely on the
result I can write unit tests for name_version() to increase confidence that
it does what I expect.
Finally I can add a docstring to make it more discoverable in the
interactive interpreter.
More information about the Python-list
mailing list