2

Let's say there is User object having field 'id', 'first_name', 'last_name', 'age' and so on.

I know that I need to sort according to one of the above mention property but I will only know the exact property at run time.

The thing I have tried

def sortBySomeSpecificKey(key_name):    
         #key_name is given to the function 
         Users = sorted(Users, key=lambda x: x.key_name, reverse=True)

The problem with this approach is, Instead of taking value of key_name, it is taking key_name as the property itself.

Please help.

Roshan Kumar
  • 453
  • 4
  • 15

1 Answers1

3

Use getattr()

Users = sorted(Users, key=lambda x: getattr(x, key_name), reverse=True)

Another option is to use functools.partial instead of lambda

from functools import partial
key = partial(gettatr, name=key_name)
Users = sorted(Users, key=key, reverse=True)

As a side note - better add argument to pass the collection instead of using global variable and return from your function.

buran
  • 13,682
  • 10
  • 36
  • 61