python – How to avoid RuntimeError: dictionary changed size during iteration error?

python – How to avoid RuntimeError: dictionary changed size during iteration error?

In Python 3.x and 2.x you can use use list to force a copy of the keys to be made:

for i in list(d):

In Python 2.x calling keys made a copy of the keys that you could iterate over while modifying the dict:

for i in d.keys():

But note that in Python 3.x this second method doesnt help with your error because keys returns an a view object instead of copynig the keys into a list.

You only need to use copy:

On thats way you iterate over the original dictionary fields and on the fly can change the desired dict (d dict).
Its work on each python version, so its more clear.

(BTW – Generally to iterate over copy of your data structure, instead of using .copy for dict or slicing [:] for list, you can use import copy -> copy.copy (for shallow copy which equivalent to copy that supported by dict or slicing [:] that supported by list) or copy.deepcopy on your data structure).

In [1]: d = {a: [1], b: [1, 2], c: [], d:[]}

In [2]: for i in d.copy():
   ...:     if not d[i]:
   ...:         d.pop(i)
   ...:         

In [3]: d
Out[3]: {a: [1], b: [1, 2]}

python – How to avoid RuntimeError: dictionary changed size during iteration error?

Just use dictionary comprehension to copy the relevant items into a new dict

>>> d
{a: [1], c: [], b: [1, 2], d: []}
>>> d = { k : v for k,v in d.iteritems() if v}
>>> d
{a: [1], b: [1, 2]}

For this in Python 3

>>> d
{a: [1], c: [], b: [1, 2], d: []}
>>> d = { k : v for k,v in d.items() if v}
>>> d
{a: [1], b: [1, 2]}

Leave a Reply

Your email address will not be published. Required fields are marked *