Iterating over a dictionary's sorted keys

Michael Hudson mwh21 at cam.ac.uk
Thu May 25 09:56:20 CEST 2000


nospam.newton at gmx.li (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?

Try:

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

[snip]
>     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?

Undoubtedly:

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

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):
    list.sort()
    return list

and then do:

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

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

Cheers,
M.

-- 
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, http://www.cs.yale.edu/homes/perlis-alan/quotes.html



More information about the Python-list mailing list