Proper deletion of selected items during map iteration in for loop: Thanks to all

Charles Hixson charleshixsn at earthlink.net
Sat Apr 26 15:25:27 EDT 2014


On 04/25/2014 10:53 AM, Charles Hixson wrote:
> What is the proper way to delete selected items during iteration of a 
> map?  What I want to do is:
>
> for (k, v) in m.items():
>    if f(k):
>       #  do some processing of v and save result elsewhere
>       del m[k]
>
> But this gives (as should be expected):
>         RuntimeError: dictionary changed size during iteration
> In the past I've accumulated the keys to be deleted in a separate 
> list, but this time there are likely to be a large number of them, so 
> is there some better way?
>

Going over the various responses, it looks like saving the "to be 
deleted" keys to a list, and then iterating over that to delete is the 
best answer.  I expect that I'll be deleting around 1/3 during each 
iteration of the process...and then adding new ones back in. There 
shouldn't be a really huge number of deletions on any particular pass, 
but it will be looped through many times...so if there were any better 
way to do this, it would speed things up considerably...but it's not 
really surprising that there doesn't appear to be.  So now it translates 
into (approximately, not yet tested):

toDel = []
for (k, v) in m.items():
    if f(k):
       #  do some processing of v and save result elsewhere
       toDel.append(k)
    else:
       # do something else
for k in toDel:
    del m[k]
toDel = None


-- 
Charles Hixson




More information about the Python-list mailing list