Sorting dict keys

"Martin v. Löwis" martin at v.loewis.de
Sun Jul 22 11:03:08 CEST 2007


> I'd like to do it in one line because what I am trying to do is, after
> all, a single, simple enough action. I find the suggested
> b = sorted(a.keys()) much more readable than breaking it up in two
> lines. 

I think you have demonstrated that a single-line statements with
multiple functions and methods is *not* more readable for you,
contrary to your own beliefs.

You were aware that sort is "in-place", and recognized that
b = d.keys().sort() does not "work". What you here failed to
recognize is that b is assigned the result of .sort(), not
the result of .keys(). You then made the same mistake again
in thinking that b=copy.copy(d.keys()).sort() should work better,
because it sorts a copy - still failing to see that it is
again the result of .sort() that gets assigned to b.

So ISTM that you got puzzled by the order in which multiple
things happen when written into a single line. My guess would
be that methods are particularly puzzling, more so than
functions (which make it somewhat more obvious that they
entirely wrap their arguments, and are entitled to return
whatever they want to).

Regards,
Martin



More information about the Python-list mailing list