[BangPypers] Python dictionaries, deleting elements while iterating.
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.
> 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:
Sometimes it is easier to create a new dictionary instead of modifying the
dictionary = dict((k, v) for k, v in dictionary.items() if v != 1)
More information about the BangPypers