[BangPypers] Python dictionaries, deleting elements while iterating.

Anand Chitipothu anandology at gmail.com
Mon Feb 25 17:03:06 CET 2013


On Mon, Feb 25, 2013 at 8:51 PM, Pranjal Mittal <
pranjal.mittal.ece10 at iitbhu.ac.in> wrote:
>
> 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.

You can iterate over items:

for key, value in dictionary.items():
    if value == 1:
        del dictionary[key]

Sometimes it is easier to create a new dictionary instead of modifying the
existing one.

dictionary = dict((k, v) for k, v in dictionary.items() if v != 1)

Anand
http://anandology.com/


More information about the BangPypers mailing list