newbie question - iterating through dictionary object
Grant Edwards
grante at visi.com
Thu Feb 17 11:49:37 EST 2005
On 2005-02-17, mirandacascade at yahoo.com <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?
Not really.
> 2) What are the tradeoffs for using each of the techniques?
"for x in a" can be more efficient since it allows the
dictionary to return key values one at a time instead of
creating a list containing all of them. For small dictionaries
it won't matter.
Here's another choice, that's sometimes handy:
>>> d = {1:'one',2:'two',3:'three'}
>>> for k,v in d.items():
.... print k,v
....
1 one
2 two
3 three
>>>
I wouldn't recommend this for large dictionaries.
--
Grant Edwards grante Yow! RELATIVES!!
at
visi.com
More information about the Python-list
mailing list