Reputation: 271774
In Django, I have a model object in a list.
[object, object, object]
Each object has ".name" which is the title of the thing.
How do I sort alphabetically by this title?
This doesn't work:
catlist.sort(key=lambda x.name: x.name.lower())
Upvotes: 6
Views: 13954
Reputation: 169304
Without the call to lower()
, the following could be considered slightly cleaner than using a lambda:
import operator
catlist.sort(key=operator.attrgetter('name'))
Add that call to lower()
, and you enter into a world of function-composition pain. Using Ants Aasma's compose()
found in an answer to this other SO question, you too can see the light that is functional programming (I'm kidding. All programming paradigms surely have their time and place.):
>>> def compose(inner_func, *outer_funcs):
... if not outer_funcs:
... return inner_func
... outer_func = compose(*outer_funcs)
... return lambda *args, **kwargs: outer_func(inner_func(*args, **kwargs))
...
>>> class A(object):
... def __init__(self, name):
... self.name = name
...
>>> L = [A(i) for i in ['aa','a','AA','A']]
>>> name_lowered = compose(operator.attrgetter('name'),
operator.methodcaller('lower'))
>>> print [i.name for i in sorted(L, key=name_lowered)]
['a', 'A', 'aa', 'AA']
Upvotes: 2