looping through the keys of a dictionary
Tim Peters
tim.one at home.com
Wed Aug 22 02:31:49 EDT 2001
[Tist Verdonck]
> Is there a way to loop through the keys of a dictionary (whitout using
> a list containing all those keys)?
Not before the not-yet-released 2.2, but why do you care? Most people
worried about speed or space in this context haven't measured either and are
simply irrational <0.7 wink>.
Under 2.2 you'll be able to do:
for k in dict: # a synonym for the next one
for k in dict.iterkeys():
for k in dict.iteritems():
for k in dict.itervalues():
None of those create a list. OTOH, if you try to *mutate* the dict while
iterating over it in these ways, you deserve whatever you get. This is the
best you can hope for:
>>> d = {1:2, 2:3}
>>> for k in d:
... d[k+2] = 3
...
Traceback (most recent call last):
File "<stdin>", line 1, in ?
RuntimeError: dictionary changed size during iteration
>>>
The great advantage to materializing a list is that it captures a snapshot
of the keys, and mutating the set of dict keys later doesn't mutate the
snapshot.
More information about the Python-list
mailing list