我有这样的obj
{hello: 'world', "foo.0.bar": v1, "foo.0.name": v2, "foo.1.bar": v3}
它应该扩展到
{ hello: 'world', foo: [{'bar': v1, 'name': v2}, {bar: v3}]}
我在下面写了代码,拆分'.'
,删除旧密钥,如果包含则附加新密钥'.'
,但它说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
对于 obj.iteritems() 中的 k,v:
RuntimeError:字典在迭代期间改变了大小