Sorting objects in Python

Posted by Curious2learn on Stack Overflow See other posts from Stack Overflow or by Curious2learn
Published on 2010-04-30T10:16:21Z Indexed on 2010/04/30 15:47 UTC
Read the original article Hit count: 362

Filed under:
|
|

I want to sort objects using by one of their attributes. As of now, I am doing it in the following way

USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True)

This works fine, but I have read that using operator.attrgetter() might be a faster way to achieve this sort. First, is this correct? Assuming that it is correct, how do I use operator.attrgetter() to achieve this sort?

I tried,

 keyFunc=operator.attrgetter('utility[chosenCar]')
 USpeople.sort(key=keyFunc,reverse=True)

However, I get an error saying that there is no attribute 'utility[chosenCar]'.

The problem is that the attribute by which I want to sort is in a dictionary. For example, the utility attribute is in the following form:

utility={chosenCar:25000,anotherCar:24000,yetAnotherCar:24500}

I want to sort by the utility of the chosenCar using operator.attrgetter(). How could I do this?

Thanks in advance.

© Stack Overflow or respective owner

Related posts about python

Related posts about sorting