can't delete from a dictionary in a loop

Eduardo O. Padoan eduardo.padoan at gmail.com
Fri May 16 18:38:52 EDT 2008


On Fri, May 16, 2008 at 6:40 PM, Gary Herron <gherron at islandtraining.com> wrote:
> bruno.desthuilliers 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:
>>>>  if procs_dict[pid].poll() != None
>>>>   # do the counter updates
>>>>   del procs_dict[pid]
>>>>      The problem:
>>>>      RuntimeError: dictionary changed size during iteration
>>>>
>>>
>>> I don't know if the setup with the pids in a dictionary is the best way
>>> to
>>> manage a pool of processes... I'll leave it others, presumably more
>>> knowledgable, to comment on that. :-)  But I can tell you how to solve
>>> the
>>> immediate problem:
>>>
>>>   for pid in procs_dict.keys():
>>>
>
> No, keys() produces a list (which is what is wanted here).
> It's iterkeys() that produces an iterator which would reproduce the OP's
> problem.
>
> And then, in Python3, keys() produces something else altogether (call a view
> of the dictionary) which would provoke the same problem, so yet another
> solution would have to be found then.

In Python 3.0, list(procs_dict.keys()) would have the same effect.



> Gary Herron
>
>>
>> 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.
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
    Eduardo de Oliveira Padoan
http://www.advogato.org/person/eopadoan/
http://twitter.com/edcrypt
Bookmarks: http://del.icio.us/edcrypt



More information about the Python-list mailing list