newbie question - iterating through dictionary object

Steven Bethard steven.bethard at gmail.com
Thu Feb 17 11:53:33 EST 2005


mirandacascade at yahoo.com wrote:
> 1) Is there any advantage to use the
> 
> y = a.keys()
> for z in y:
> 
> looping technique rather than the
> 
> for x in a:
> 
> looping technique?
> 
> 2) What are the tradeoffs for using each of the techniques?

Calling dict.keys creates a list in memory of the keys to the dict. 
Using the dict directly in the for-loop (which implicitly calls 
__iter__) will only load one key into memory at a time.  The only time 
you should call keys is if you *really* need a list.  If you're just 
going to iterate over them in a for-loop, you should definitely use the 
latter technique.

STeVe



More information about the Python-list mailing list