Another dict method...
Alex Martelli
aleaxit at yahoo.com
Sat May 19 03:51:15 EDT 2001
"Stephen Hansen" <news at myNOSPAM.org> wrote in message
news:imnN6.41384$154.11548822 at typhoon.we.rr.com...
> ... Dictionaries aren't sorted, and I can't imagine an iterator is going
to
> go through the trouble of sorting them. Even with iterators, if you wish
to
> iterate over a dictionary in sorted order, you'll have to do what you do
> now, I believe... that is, extract the .keys() and sort them, then iterate
> over them.
>
> for key in dict.keys().sort()
No -- the .sort() method sorts a list in-place and returns None. You
need a little auxiliary function:
def sorted_inplace(alist):
alist.sort()
return alist
for key in sorted_inplace(dict.keys()):
No need to make a copy of the list before sorting it, in this case, as it's
a temporary list. To avoid altering other lists, in other cases you might
prefer the following auxiliary function:
def sorted_copy(alist):
return sorted_inplace(alist[:])
where the whole-list-slice [:] is the normal idiom to copy a list.
Alex
More information about the Python-list
mailing list