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

David Harrison dave.l.harrison at
Wed Apr 9 05:26:28 CEST 2008

On 09/04/2008, Jason <elgrandchignon at> 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,


class Foo:
    def __init__(self, value):
        self.value = value

    def __repr__(self):
        return self.value

a = [Foo('c'), Foo('B'), Foo('A')]

print sorted(
    cmp=lambda x,y: cmp(x.lower(), y.lower()),
    key=lambda x: x.value

More information about the Python-list mailing list