Iterating over a dictionary's sorted keys

Michael Hudson mwh21 at
Thu May 25 03:56:20 EDT 2000

nospam.newton at (Philip 'Yes, that's my address' Newton) writes:

> Hi there,
> In the other P language, the standard idiom is
>     for $key (sort keys %d) { ... }                # (1)
> The naive approach in Python would be
>     for key in d.keys().sort(): pass               # (2)
> However, this doesn't make sense (I realise this). I presume that this
> makes a temporary list containing the keys of d, sorts this list, throws
> the list away and then does the equivalent of 'for k in None: pass'.
> _Learning Python_ suggests the following in its solution to example 3 of
> chapter 3:
>     keys = d.keys
>     keys.sort()
>     for key in keys: pass # whatever               # (3)
> Is there any way to avoid this temporary variable and to write the for
> in one line?


for key in (lambda k: k.sort() or k)(d.keys()):

>     for key in (lambda k=d.keys(): k.sort() or k)(): print key, # (8)

Oh, you thought of that :-).
> What's the standard Python idiom for this? What do you use?


keys = d.keys()
for key in keys:

Are you allergic to the newline character or something?  This is
clear, and says exactly what you want to do.

If you really really need to do it on one line, why not define:

def sorted(list):
    return list

and then do:

for key in sorted(d.keys()):

This is obviously fundamentally the same as #(8), but is rather more


48. The best book on programming for the layman is "Alice in
    Wonderland";  but  that's because it's  the best book on 
    anything for the layman.
  -- Alan Perlis,

More information about the Python-list mailing list