Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #70610

Re: Proper deletion of selected items during map iteration in for loop

Date 2014-04-25 19:04 +0100
From Matthew Barnett <mrabarnett@mrabarnett.plus.com>
Subject Re: Proper deletion of selected items during map iteration in for loop
References <535AA12A.1030203@earthlink.net>
Newsgroups comp.lang.python
Message-ID <mailman.9506.1398449083.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 2014-04-25 18:53, 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?
>
The other way is to build a new dictionary.

Actually, there's a third way. Iterate over a snapshot:

for (k, v) in list(m.items()):
     if f(k):
         #  do some processing of v and save result elsewhere
         del m[k]

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Proper deletion of selected items during map iteration in for loop Matthew Barnett <mrabarnett@mrabarnett.plus.com> - 2014-04-25 19:04 +0100

csiph-web