tags:

views:

103

answers:

3

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!

+2  A: 

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.

Blair Conrad
+3  A: 
>>> 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.

SilentGhost
+7  A: 

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.

extraneon
I like this better than what I was doing. Thanks!
Wes