Why is this code to delete negative values from a dictionary not working?

Viewed 4572

I have to get rid of all the entries which have negative value. Why is my code not working?

dic = {'aa': 20, 'bb': -10, 'cc': -12}

for i in dic:
    if dic[i] < 0:
        del dic[i]
        
print(dic)

When running this code I get an exception:

RuntimeError: dictionary changed size during iteration

5 Answers

This should work in Python 2.x - substituting the for loop with

 for i in dic.keys():
   if dic[i]<0:
    del dic[i]

The reason why this doesn't work in Python 3.x is that keys returns an iterator instead of a list-- I found an explanation in https://stackoverflow.com/a/11941855/2314737

Quite a subtle difference--I didn't know that.

So, in Python 3.x you would need to use

for i in list(dic):
delete_list = []
for i in dic:
    if dic[i] < 0:
        delete_list.append(i)
for each in delete_list:
    del dic[each]

Using dict.pop():

myDict = {'aa': 20, 'bb': -10, 'cc': -12}
condition = []

for x, y in myDict.items ():
    if y <  0:
        condition.append(x)
        
[myDict.pop(x) for x in condition ]

print(myDict)

gives

{'aa': 20}
d = {}
# ...

keys = list(d.keys())

for key in keys:
  if something_is_true:
    del d[key]
Related