I have obj like this
JavaScript
x
2
1
{hello: 'world', "foo.0.bar": v1, "foo.0.name": v2, "foo.1.bar": v3}
2
It should be expand to
JavaScript
1
2
1
{ hello: 'world', foo: [{'bar': v1, 'name': v2}, {bar: v3}]}
2
I wrote code below, splite by '.'
, remove old key, append new key if contains '.'
, but it said RuntimeError: dictionary changed size during iteration
JavaScript
1
18
18
1
def expand(obj):
2
for k in obj.keys():
3
expandField(obj, k, v)
4
5
def expandField(obj, f, v):
6
parts = f.split('.')
7
if(len(parts) == 1):
8
return
9
del obj[f]
10
for i in xrange(0, len(parts) - 1):
11
f = parts[i]
12
currobj = obj.get(f)
13
if (currobj == None):
14
nextf = parts[i + 1]
15
currobj = obj[f] = re.match(r'd+', nextf) and [] or {}
16
obj = currobj
17
obj[len(parts) - 1] = v
18
for k, v in obj.iteritems():
RuntimeError: dictionary changed size during iteration
Advertisement
Answer
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.