Sort list of dictionaries by key (case insensitive)
Peter Otten
__peter__ at web.de
Wed Jan 13 07:25:24 EST 2010
Nico Grubert wrote:
>> Er, that should have been mylist.sort(key = lambda d:
>> d['title'].lower()) of course.
>
>
> Thanks a lot for the tip, chris.
> Unfortunately, I only have Python 2.3.5 installed and can't upgrade to
> 2.4 due to an underliying application server.
>
> In python 2.3 the 'sort()' function does not excepts any keywords
> arguments (TypeError: sort() takes no keyword arguments), so is there a
> workaround?
There is a technique called decorate-sort-undecorate:
>>> def sorted(items, key):
... decorated = [(key(item), index, item) for index, item in
enumerate(items)]
... decorated.sort()
... return [item[2] for item in decorated]
...
>>> items = "Atem Äther ähnlich anders".split()
>>> print " ".join(sorted(items, key=lambda s: s.lower()))
anders Atem Äther ähnlich
>>> print " ".join(sorted(items, key=lambda s: locale.strxfrm(s)))
ähnlich anders Atem Äther
The above may run on 2.3, but I actually ran it on 2.6.
Peter
More information about the Python-list
mailing list