python RuntimeError: dictionary changed size during iteration

python

Solution

Like the message says: you changed the number of entries in obj inside of expandField() while in the middle of looping over this entries in expand.

You might try instead creating a new dictionary of the form you wish, or somehow recording the changes you want to make, and then making them AFTER the loop is done.

Problem

I have obj like this ``` {hello: 'world', "foo.0.bar": v1, "foo.0.name": v2, "foo.1.bar": v3} ``` It should be expand to ``` { hello: 'world', foo: [{'bar': v1, 'name': v2}, {bar: v3}]} ``` I wrote code below, splite by `'.'`, remove old key, append new key if contains `'.'`, but it said `RuntimeError: dictionary changed size during iteration` ``` def expand(obj): for k in obj.keys(): expandField(obj, k, v) def expandField(obj, f, v): parts = f.split('.') if(len(parts) == 1): return del obj[f] for i in xrange(0, len(parts) - 1): f = parts[i] currobj = obj.get(f) if (currobj == None): nextf = parts[i + 1] currobj = obj[f] = re.match(r'\d+', nextf) and [] or {} obj = currobj obj[len(parts) - 1] = v ``` for k, v in obj.iteritems(): RuntimeError: dictionary changed size during iteration

Original source

Related problems