On Apr 8, 8:26 pm, "David Harrison" <[EMAIL PROTECTED]> wrote: > On 09/04/2008, Jason <[EMAIL PROTECTED]> wrote: > > > Hi folks-- > > > Basically, I have a pressing need for a combination of 5.2 "Sorting a > > List of Strings Case-Insensitively" & 5.3 "Sorting a List of Objects > > by an Attribute of the Objects" from the Python Cookbook. > > > My first guess isn't working: > > > import operator > > def sort_by_attr(seq, attr): > > key=operator.attrgetter(attr) > > key=str.lower > > return sorted(seq, key) > > > ...would much appreciate any guidance! > > You're probably looking for the built-in function sorted, > > e.g. > > class Foo: > def __init__(self, value): > self.value = value > > def __repr__(self): > return self.value > > a = [Foo('c'), Foo('B'), Foo('A')] > > print sorted( > a, > cmp=lambda x,y: cmp(x.lower(), y.lower()), > key=lambda x: x.value > )
Hey-- thanks! I actually figured out something that works quite nicely since I posted: def sort_by_attr_case_insensitive(seq, attr): return sorted(seq, cmp=lambda x,y: cmp(x.lower(), y.lower()), key=operator.attrgetter(attr)) -- http://mail.python.org/mailman/listinfo/python-list