Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #70639
| Date | 2014-04-26 12:25 -0700 |
|---|---|
| From | Charles Hixson <charleshixsn@earthlink.net> |
| Subject | Re: Proper deletion of selected items during map iteration in for loop: Thanks to all |
| References | <535AA12A.1030203@earthlink.net> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.9524.1398540343.18130.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Charles Hixson <charleshixsn@earthlink.net> - 2014-04-26 12:25 -0700
Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-04-27 02:14 +0000
Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Chris Angelico <rosuav@gmail.com> - 2014-04-27 12:49 +1000
Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Duncan Booth <duncan.booth@invalid.invalid> - 2014-04-28 10:48 +0000
Re: Proper deletion of selected items during map iteration in for loop: Thanks to all Roy Smith <roy@panix.com> - 2014-04-26 22:57 -0400
csiph-web