[BangPypers] Python dictionaries, deleting elements while iterating

Thava Alagu thavamuni at gmail.com
Mon Feb 25 18:17:06 CET 2013


Hi,

  Earlier answers have rightly pointed out elegant solutions,
out of which dictionary comprehension is the most pythonic.
btw, dictionary comprehension is available in Python 2.7 and 3+.

with regards to why deleting while iterating is a problem --
it is like cutting the branch of the tree while standing on it.

For efficiency reasons, the python implementations of iterators are
free to use some sort of linked list like representation for iterators--
when you delete the current element the iterator gets confused
how to go to next element.

Regards,
-thava

On Mon, Feb 25, 2013 at 10:15 PM,  <bangpypers-request at python.org> wrote:

> Message: 4
> Date: Mon, 25 Feb 2013 20:51:58 +0530
> From: Pranjal Mittal <pranjal.mittal.ece10 at iitbhu.ac.in>
> To: Bangalore Python Users Group - India <bangpypers at python.org>
> Subject: [BangPypers] Python dictionaries, deleting elements while
>         iterating.
> Message-ID:
>         <CALiP1o+dd5uR+nGdoG4peCdFtd6MyhhcToP7yTi_-JQVuDrZ+Q at mail.gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> Hi all,
>
> I was writing a piece of code that deletes items from Python Dictionaries
> when a certain condition is met. while iterating over the dictionary.
>
> http://dpaste.com/hold/995010/
>
> However that leads to a RunTime Error.
> Though I figured out an alternate solution, I still wonder why shouldn't
> something like *Case-1 *(in the code) work ideally.
>
>
>
> - Pranjal Mittal
>
> --
> B.Tech. Part III,
> Indian Institute of Technology, BHU,
> Varanasi -221005


More information about the BangPypers mailing list