sorting dictionary keys?
Emile van Sebille
emile at fenx.com
Sat Nov 29 16:52:02 EST 2003
John Smith
> Hi, what's the fastest way (least amount of typing) to sort
dictionary
> objects by the key? What's the fastest way of iterating over sorted
keys
> for a dictionary in terms of performance? Are the two equivalent?
>
> The way I have been doing it is:
>
> d = {}
> #populate d
> keys = d.keys()
> keys.sort()
> for k in keys:
> print k, d[k]
>
> but I would like to do:
> #error here
> for k in d.keys().sort():
sort sorts in place and doesn't return anything. In 2.4 you'll have
the sorted method.
> print k, d[k]
>
> why doesn't the nested function call work? Thanks in advance.
>
>
The shortest thing to type? You're there with s = d.keys() and
s.sort().
--
Emile van Sebille
emile at fenx..com
More information about the Python-list
mailing list