I want to sort objects using one of their attributes. At the moment I am doing it as follows
USpeople.sort(key=lambda person: person.utility[chosenCar],reverse=True)
This works fine, but I read that using operator.attrgetter () can be a faster way to achieve this kind of thing. Firstly, is this correct? Assuming this is correct, how can I use operator.attrgetter () to achieve this kind?
I tried,
keyFunc=operator.attrgetter('utility[chosenCar]')
USpeople.sort(key=keyFunc,reverse=True)
However, I get an error message indicating that the attribute 'utility [selectedCar] does not exist.
The problem is that the attribute by which I want to sort is in the dictionary. For example, a utility attribute has the following form:
utility={chosenCar:25000,anotherCar:24000,yetAnotherCar:24500}
I want to sort using the selectedCar utility with operator.attrgetter (). How can i do this?
Thanks in advance.