6

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())
1
  • 1
    It would help if you read error messages, the one for your code points exactly on the dot in x.name Commented May 27, 2010 at 23:31

2 Answers 2

12
catlist.sort(key=lambda x: x.name.lower())
Sign up to request clarification or add additional context in comments.

Comments

2

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.