newbie question - iterating through dictionary object
mirandacascade at yahoo.com
mirandacascade at yahoo.com
Thu Feb 17 11:14:26 EST 2005
I am attempting to understand the difference between two techniques
that use a for/in loop to iterate through entries in a dictionary
object. Copy/paste of interactive window illustrates.
>>> a = {}
>>> a.update({1:'a'})
>>> a.update({2:'b'})
>>> a
{1: 'a', 2: 'b'}
>>> for x in a:
... print x
... print a[x]
...
1
a
2
b
>>> y = a.keys()
>>> for z in y:
... print z
... print a[z]
...
1
a
2
b
The techniques appear to return the same results. In the first
example, for each loop iteration, x appears to have the value of the
key of the dictionary object. In the second example, z appears to have
the value of the key in the dictionary object. Assuming that I want to
iterate through each dictionary entry, and I don't care about the order
in which the code iterates (i.e. I don't need to sort the list that
gets returned to y when it is assigned the value of the expression
a.keys()), my questions are:
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?
More information about the Python-list
mailing list