Issue
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
You can accomplish this by using dict comprehensions.
dic = {k: v for (k, v) in dic.items() if v >= 0}
Answered By - Steinar Lima
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.