Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #70614 > unrolled thread
| Started by | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| First post | 2014-04-25 14:50 -0400 |
| Last post | 2014-04-25 14:50 -0400 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Proper deletion of selected items during map iteration in for loop Terry Reedy <tjreedy@udel.edu> - 2014-04-25 14:50 -0400
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Date | 2014-04-25 14:50 -0400 |
| Subject | Re: Proper deletion of selected items during map iteration in for loop |
| Message-ID | <mailman.9510.1398451902.18130.python-list@python.org> |
On 4/25/2014 2:04 PM, Matthew Barnett wrote: > 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. If you expect to delete more than half the keys *and* if there are no other references to the dict, such that you need the particular object mutated, this might be better. > 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] Since a pre-snapshot of items or even just keys will be longer than a list of keys to be deleted, I would stick with the latter. -- Terry Jan Reedy
Back to top | Article view | comp.lang.python
csiph-web