Iterating over a dictionary's sorted keys

Robert Roy rjroy at takingcontrol.com
Fri May 26 13:38:02 EDT 2000


On Thu, 25 May 2000 19:44:29 GMT, nospam.newton at gmx.li (Philip 'Yes,
that's my address' Newton) wrote:

>On 25 May 2000 08:56:38 GMT, scarblac-spamtrap at pino.selwerd.nl (Remco
>Gerlich) wrote:
>
>> All your other approaches create lots of temporary stuff too.
>
>But not named temporary stuff that sticks around.

Then get rid of the named stuff afterwards.

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

    # now that you're done  with keys
    # you can get rid of the list
    keys = None

Remember that this is a list of references (dare I say pointers?) so
it may not be taking up as much memory as you think.

Bob
>
>> Why the problem with multiple lines and an extra variable here and there?
>
>Philosophy, I suppose. Got a few idioms from the functional-programming
>style and liked the conciseness involved. Like using map instead of
>looping by yourself. Or the Schwartzian Transform in Perl, rather than
>using lots of temporary variables and more lines -- it's become a
>standard idiom now.
>
>I don't want to have an unsorted version of the keys of a dictionary
>around -- I just want the result.
>


>I suppose "for key in sorted(d.keys()): pass" is the closest to what I
>want while balancing the needs of readability and one-line-ness.
>
>Cheers,
>Philip
>-- 
>Philip Newton <nospam.newton at gmx.li>
>If you're not part of the solution, you're part of the precipitate.




More information about the Python-list mailing list