Sort list of dictionaries

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Mar 3 02:55:08 EST 2015


Charles Heizer wrote:

> Hello,
> I'm new to python and I'm trying to find the right way to solve this issue
> I have.
> 
> I'm trying to sort this list by name and then by version numbers. The
> problem I'm having is that I can not get the version numbers sorted with
> the highest at the top or sorted properly.
> 
> mylist = [{'name': u'com.google.earth', 'version': u'7.1.2.2041'},
> {'name': u'com.google.earth', 'version': u'7.1.2.2019'},
> {'name': u'com.google.Chrome', 'version': u'40.0.2214.93'},
> {'name': u'com.google.Chrome', 'version': u'40.0.2214.91'},
[...]
> ]
> 
> sortedlist = sorted(mylist , key=lambda x, y: x['name']
> LooseVersion(elem['version'])), reverse=True)

There's a syntax error there. Is there supposed to be a comma between the 
x['name'] and the LooseVersion function call?

Once you've fixed the syntax error, you can then fix the mysterious elem, 
and the fact that your key function takes too many arguments.

The key function should take *one* argument, which in your case is a dict. 
So:

def sort_by_version(d):
    name = d['name']
    version = d['version']
    return (name, [int(substr) for substr in version.split('.')])


sortedlist = sorted(mylist, key=sort_by_version)


should get you started. It may not quiet do what you want, but you can 
adjust the sort_by_version function as needed.



-- 
Steve




More information about the Python-list mailing list