user2384994
user2384994

Reputation: 1847

Is it possible to delete keys meeting some criterion using a simple iteration in Python3?

Suppose we have a dict d={"key1":-1,"key2":-2,"key3":3,"key4":0,"key5":-7,"key6":1,...} in python3. Now I want to delete keys whose value is negative, e.g.,"key1":-1,"key2":-2,etc. I tried to write a code like this:

for k in d:
    if d[k]<0:
       del d[k]

But I received error saying "RuntimeError: dictionary changed size during iteration". From this message, it seems that it is not possible to delete keys of a dictionary meeting some criterion using a simple iteration, so at the moment, I have to save the keys to be deleted in a list, then write another iteration to remove them from d. My question is: is it really impossible to remove some of keys using a single iteration? If it's possible, could you please give a sample code of Python3 that can remove keys meeting some criterion using a simple iteration in Python3? Thank you.

Upvotes: 3

Views: 70

Answers (2)

jwodder
jwodder

Reputation: 57490

Iterate over the keys instead of the dict:

for k in d.keys():
    if d[k]<0:
        del d[k]

For this to work in Python 3.X, keys() returns an iterator, so you need to use the following first line:

for k in list(d.keys()):

Upvotes: 1

DSM
DSM

Reputation: 353129

Method #1: use a dictionary comprehension. This doesn't delete so much as replace, but gets you to the same d.

>>> d = {"key1":-1,"key2":-2,"key3":3,"key4":0,"key5":-7}
>>> d = {k: v for k,v in d.items() if v >= 0}
>>> d
{'key3': 3, 'key4': 0}

Method #2: iterate over an independent copy of the keys:

>>> d = {"key1":-1,"key2":-2,"key3":3,"key4":0,"key5":-7}
>>> for k in set(d):
...     if d[k] < 0:
...         del d[k]
...         
>>> d
{'key3': 3, 'key4': 0}

Upvotes: 3

Related Questions