dictionary issue (and maybe PEP ... depending on the answer)

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Jun 4 16:47:08 CEST 2003


Ian Bicking <ianb at colorstudy.com> wrote in 
news:mailman.1054699476.25695.python-list at python.org:

> On Mon, 2003-06-02 at 00:45, dsavitsk wrote:
>> never mind, for now, that there are proably better ways to do what the 
>> dict obviously does.  anyhow, I get a list of the months by doing this
>> 
>>  >>> [_months[i] for i in _months.keys()]
> 
> Now what I'd like is:
> 
> [m for m, i in _months.items() sortby i]
> 
> Such an addition to list comprehension would make everyone who doesn't
> like the sort method happy, plus it's just a much better way to express
> sorting, so you could do things like:
> 
> [p for p in people sortby p.lastname, p.firstname]
> 
> instead of:
> 
> l = people[:]
> l.sort(lambda a, b: cmp((a.lastname, a.firstname), 
>                         (b.lastname, b.firstname))
> 
You mean instead of:
l = [ p.lastname, p.firstname, index, p
      for (index, p) in enumerate(people)]
l.sort()
l = [ p[3] for p in l ]

But this proposal only goes half way, if you are going to do this you want 
to be able to specify ascending/descending for each key as well.

   [p for p in people sortby p.lastname ASC, p.firstname DESC]

Actually, it did occur to me a little while back that it is possible to 
create an object that wraps any object but inverts the sense of 
comparisons. So it ought to be possible to implement descending sorts by 
wrapping the keys in an object of this type, so sorting on lastname 
ascending, firstname descending, and also stable could be done using such 
an object of type reversesort by:

   [p for p in people sortby p.lastname, reversesort(p.firstname)]

as a shorthand for

   l = [ p.lastname, reversesort(p.firstname), index, p
         for (index, p) in enumerate(people)]
   l.sort()
   l = [ p[3] for p in l ]


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list