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

dictionary, python, python-3.x

Solution

You can accomplish this by using dict comprehensions.

dic = {k: v for (k, v) in dic.items() if v >= 0}

Problem

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

Original source

Related problems