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

Peter Otten __peter__ at web.de
Wed Apr 9 09:31:06 CEST 2008


Paddy wrote:

> On Apr 9, 4:04 am, 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!
> 
> HiJason,
> Try  key= lambda x: x.attr.lower()
> The above should calculate the key only once for the items to be
> sorted rather than using cmp which calculates more than that.

A key func is indeed preferable over cmp. Here is a working example:

>>> import operator
>>> class A(object):
...     def __init__(self, name, value):
...             self.name = name
...             self.value = value
...     def __repr__(self):
...             return "%s|%s" % (self.name, self.value)
...
>>> items = [A("a", "z"), A("C", "Y"), A("b", "x")]
>>> items
[a|z, C|Y, b|x]
>>> def sorted_by_attr_icase(items, attrname):
...     get = operator.attrgetter(attrname)
...     return sorted(items, key=lambda item: get(item).lower())
...
>>> sorted_by_attr_icase(items, "name")
[a|z, b|x, C|Y]
>>> sorted_by_attr_icase(items, "value")
[b|x, C|Y, a|z]

Peter



More information about the Python-list mailing list