Re: Sort list of dictionaries by key (case insensitive)

Discussion in 'Python' started by Nico Grubert, Jan 13, 2010.

  1. Nico Grubert

    Nico Grubert Guest


    > 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?

    Regards
    Nico
    Nico Grubert, Jan 13, 2010
    #1
    1. Advertising

  2. Nico Grubert

    Peter Otten Guest

    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
    Peter Otten, Jan 13, 2010
    #2
    1. Advertising

  3. Peter Otten, 13.01.2010 13:25:
    > >>> items = "Atem Äther ähnlich anders".split()
    > >>> print " ".join(sorted(items, key=lambda s: s.lower()))


    If you can make sure that 's' is either always a byte string or always a
    unicode string (which is good programming practice anyway), an unbound
    method can simplify (and speed up) the above, e.g.

    sorted(items, key=unicode.lower)

    Stefan
    Stefan Behnel, Jan 13, 2010
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Tee
    Replies:
    3
    Views:
    7,803
    Herfried K. Wagner [MVP]
    Jun 23, 2004
  2. Replies:
    1
    Views:
    2,479
    Mark P
    Apr 6, 2007
  3. Nico Grubert
    Replies:
    2
    Views:
    338
    Florian Diesch
    Jan 13, 2010
  4. Nico Grubert
    Replies:
    2
    Views:
    377
    Peter Otten
    Jan 13, 2010
  5. san
    Replies:
    2
    Views:
    215
    Prasad, Ramit
    Nov 27, 2012
Loading...

Share This Page