Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete an entry from a dictionary (Python)

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

like image 698
prithajnath Avatar asked Dec 06 '13 07:12

prithajnath


4 Answers

You can accomplish this by using dict comprehensions.

dic = {k: v for (k, v) in dic.items() if v >= 0}
like image 190
Steinar Lima Avatar answered Oct 31 '22 17:10

Steinar Lima


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):
like image 42
user2314737 Avatar answered Oct 31 '22 16:10

user2314737


delete_list = []
for i in dic:
    if dic[i] < 0:
        delete_list.append(i)
for each in delete_list:
    del dic[each]
like image 28
MarshalSHI Avatar answered Oct 31 '22 17:10

MarshalSHI


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}
like image 36
Subham Avatar answered Oct 31 '22 17:10

Subham