Sorting a List of Objects by an Attribute of the Objects Case-Insensitively

Jason elgrandchignon at gmail.com
Tue Apr 8 23:33:23 EDT 2008


On Apr 8, 8:26 pm, "David Harrison" <dave.l.harri... at gmail.com> wrote:
> On 09/04/2008, Jason <elgrandchig... at gmail.com> 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))



More information about the Python-list mailing list