Reputation: 1854
I am new to Python and am curious if I am doing this correctly. I have a tuple of dicts (from a database call):
companies = ( { 'companyid': 1, 'companyname': 'Company C' },
{ 'companyid': 2, 'companyname': 'Company A' },
{ 'companyid': 3, 'companyname': 'Company B' } )
I want to sort this on companyname. Is there a more correct way than this to do it?
sortcompanies = list(companies)
sortcompanies.sort(lambda x,y: cmp(x['companyname'],y['companyname']))
Thanks for your criticism!
Upvotes: 3
Views: 200
Reputation: 23980
You could do something like:
import operator
...
sortcompanies.sort(key=operator.itemgetter("companyname"))
I think that's a matter of taste.
EDIT
I got companyid
in stead of companyname
. Corrected that error.
Upvotes: 7
Reputation: 242130
That's fine, but you might want to consider sorting by keys:
sortcompanies.sort(key=lambda x:x['companyname'])
instead. It's a little easier to read, and there will be fewer calls to x['companyname']
.
@extraneon makes a good point about using operator.itemgetter
as your key. That's pretty readable as well.
Upvotes: 2
Reputation: 320039
>>> companies = ( { 'companyid': 1, 'companyname': 'Company C' },
{ 'companyid': 2, 'companyname': 'Company A' },
{ 'companyid': 3, 'companyname': 'Company B' } )
>>> sorted(companies, key=lambda x: x['companyname'])
[{'companyname': 'Company A', 'companyid': 2}, {'companyname': 'Company B', 'companyid': 3}, {'companyname': 'Company C', 'companyid': 1}]
as you'll see when reading the docs of sorted
first argument to the sorted
might be any iterable, so you might not need even create the tuple.
Upvotes: 3