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
You can accomplish this by using dict comprehensions.
dic = {k: v for (k, v) in dic.items() if v >= 0}
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With