can't delete from a dictionary in a loop

Hans Nowak zephyrfalcon!NO_SPAM! at gmail.com
Fri May 16 17:51:12 EDT 2008


bruno.desthuilliers at gmail.com wrote:
> On 16 mai, 23:34, "bruno.desthuilli... at gmail.com"
> <bruno.desthuilli... at gmail.com> wrote:
>> On 16 mai, 23:28, Hans Nowak <zephyrfalcon!NO_SP... at gmail.com> wrote:
>>
>>
>>> Dan Upton wrote:
>>>> for pid in procs_dict:
> (snip)
>>>    for pid in procs_dict.keys():
>> I'm afraid this will do the same exact thing. A for loop on a dict
>> iterates over the dict keys, so both statements are strictly
>> equivalent from a practical POV.
> 
> Hem. Forget it. I should think twice before posting - this will
> obviously make a big difference here.  Sorry for the noise.

:-)  It appears that you would be right if this was Python 3.0, though:

Python 3.0a5 (r30a5:62856, May 16 2008, 11:43:33)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
 >>> d = {1: 2, 3: 4, 5: 6}
 >>> for i in d.keys(): del d[i]
...
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

Maybe 'for i in d' and 'for i in d.keys()' *are* functionally equivalent in 3.0, 
as d.keys() returns an object that iterates over d's keys... but I haven't read 
enough about it yet to be sure.  In any case, the problem goes away when we 
force a list:

 >>> d = {1: 2, 3: 4, 5: 6}
 >>> for i in list(d.keys()): del d[i]
...
 >>> d
{}

--Hans



More information about the Python-list mailing list