Proper deletion of selected items during map iteration in for loop

C

Charles Hixson

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?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top