Sort a list of objects by an attribute given a string of the name of the attribute

So far:

def sort_by(column):
    for order in sorted(orders, key=lambda order: order.column):
        ...

list('ratio')

Clearly both ratio and 'ratio' are illegal arguments here. I think Django and most other python web frameworks do something like this internally. Is there a pattern for this?

Upvotes: 0

Views: 383

Answers (2)

jscs
jscs

Reputation: 64002

def arrange_list(column):
    for order in sorted(orders, key=lambda order: order.__dict__[column]):
        ...

should do the trick.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

sorted(..., key=operator.attrgetter(column))

Upvotes: 3

Related Questions