-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
  • 5,370
  • 8
  • 47
  • 75
David542
  • 104,438
  • 178
  • 489
  • 842

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,797
  • 3
  • 21
  • 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
  • 104,438
  • 178
  • 489
  • 842
  • 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