'Why is this code to delete negative values from a dictionary not working?
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
Solution 1:[1]
You can accomplish this by using dict comprehensions.
dic = {k: v for (k, v) in dic.items() if v >= 0}
Solution 2:[2]
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):
Solution 3:[3]
delete_list = []
for i in dic:
if dic[i] < 0:
delete_list.append(i)
for each in delete_list:
del dic[each]
Solution 4:[4]
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}
Solution 5:[5]
d = {}
# ...
keys = list(d.keys())
for key in keys:
if something_is_true:
del d[key]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Community |
| Solution 3 | MarshalSHI |
| Solution 4 | Subham |
| Solution 5 | shioko |
