-2

How would I remedy the following error?

for item in data:
    if data[item] is None:
        del data[item]

RuntimeError: dictionary changed size during iteration

It doesn't actually seem to affect my operation, so I'm wondering if perhaps I should just ignore this error?

user
  • 4,960
  • 7
  • 46
  • 70
David542
  • 101,766
  • 154
  • 423
  • 727

2 Answers2

-1

You have to move changing dictionary to another vairable:

changing_data = data
for item in data:
  if changing_data[item] is None:
    del changing_data[item]
data = changing_data
Alexander Perechnev
  • 2,711
  • 2
  • 19
  • 35
-1

This seems to be a matter of needing to change the item to be iterated over from the dictionary to the keys of the dictionary:

for key in data.keys():
    if data[key] is None:
        del data[key]

Now it doesn't complain about iterating over an item that has changed size during its iteration.

David542
  • 101,766
  • 154
  • 423
  • 727
  • It works in python 2.x, but not in 3.x. :( – 7stud Jan 31 '15 at 23:33
  • However, ... if you convert the keys() to a list, then it will work in python 3.x.: `for key in list(data.keys()):` Because python 3.x uses *views* of the data, when you delete something from the dict, then what the view sees also changes. But a list of the keys does not change as you delete things from the dict, so iterating over a list of keys does not cause an iteration problem. – 7stud Jan 31 '15 at 23:45
  • @7stud that makes sense. Would you want to post your own answer here describing this all and I'll accept yours? – David542 Feb 01 '15 at 00:18