Iterating over a dictionary's sorted keys

Huaiyu Zhu hzhu at rocket.knowledgetrack.com
Sat May 27 00:42:49 CEST 2000


On Thu, 25 May 2000 04:20:08 GMT, Philip 'Yes, that's my address' Newton
<nospam.newton at gmx.li> wrote: 
>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'.

Python returns None to remind users that sort is in place.
This does what you want

def sort(a):
    a.sort()
    return a

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

Huaiyu



More information about the Python-list mailing list