简体   繁体   English

python RuntimeError:字典在迭代期间改变了大小

[英]python RuntimeError: dictionary changed size during iteration

I have obj like this我有这样的 obj

{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 ,但它说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():对于 obj.iteritems() 中的 k, v:

RuntimeError: dictionary changed size during iteration运行时错误:字典在迭代期间改变了大小

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.就像消息说的那样:您在 expandField() 中更改了 obj 中的条目数,同时在 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.您可以尝试创建一个您希望的形式的新字典,或者以某种方式记录您想要进行的更改,然后在循环完成后进行更改。

You might want to copy your keys in a list and iterate over your dict using the latter, eg:您可能希望将您的密钥复制到列表中并使用后者迭代您的 dict,例如:

def expand(obj):
    keys = obj.keys()
    for k in keys:
        expandField(obj, k, v)

I let you analyse if the resulting behavior suits your expected results.我让您分析由此产生的行为是否符合您的预期结果。

I had a similar issue with wanting to change the dictionary's structure (remove/add) dicts within other dicts.我想在其他字典中更改字典的结构(删除/添加)字典时遇到了类似的问题。

For my situation I created a deepcopy of the dict.对于我的情况,我创建了字典的深层副本。 With a deepcopy of my dict, I was able to iterate through and remove keys as needed.使用我的字典的深层副本,我能够根据需要迭代和删除键。 Deepcopy - PythonDoc Deepcopy - PythonDoc

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.深拷贝构造一个新的复合对象,然后递归地将原始对象中的对象的副本插入其中。

Hope this helps!希望这可以帮助!

Rewriting this part重写这部分

def expand(obj):
    for k in obj.keys():
        expandField(obj, k, v)

to the following到以下

def expand(obj):
    keys = obj.keys()
    for k in keys:
        if k in obj:
            expandField(obj, k, v)

shall make it work.将使它工作。

For those experiencing对于那些经历

RuntimeError: dictionary changed size during iteration

also make sure you're not iterating through a defaultdict when trying to access a non-existent key!还要确保在尝试访问不存在的密钥时没有遍历defaultdict I caught myself doing that inside the for loop, which caused the defaultdict to create a default value for this key, causing the aforementioned error.我发现自己在for循环中这样做,这导致defaultdict为该键创建默认值,从而导致上述错误。

The solution is to convert your defaultdict to dict before looping through it, ie解决方案是在循环之前将defaultdict转换为dict ,即

d = defaultdict(int)
d_new = dict(d)

or make sure you're not adding/removing any keys while iterating through it.或者确保在迭代时没有添加/删除任何键。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python,RuntimeError:字典在迭代过程中更改了大小 - Python, RuntimeError: dictionary changed size during iteration RuntimeError:字典在python迭代期间更改了大小 - RuntimeError: dictionary changed size during iteration in python 如何解决这个python错误? RuntimeError:字典在迭代期间改变了大小 - How to fix this python error? RuntimeError: dictionary changed size during iteration RuntimeError:词典在迭代过程中更改了大小 - RuntimeError: dictionary changed size during iteration RuntimeError:字典在迭代期间使用 defaultdict() 改变了大小 - RuntimeError : dictionary changed size during iteration with defaultdict() RuntimeError:迭代期间字典改变了大小 - 在defaultdict上使用iteritems进行迭代 - RuntimeError: dictionary changed size during iteration - During Iteration with iteritems on a defaultdict “RuntimeError:字典在迭代期间改变了大小”但它在循环中没有改变 - "RuntimeError: dictionary changed size during iteration" but it's not changed in the loop RuntimeError:字典在迭代过程中更改了大小-如何解决? - RuntimeError: dictionary changed size during iteration - how to solve? 如何避免“RuntimeError: dictionary changed size during iteration”错误? - How to avoid "RuntimeError: dictionary changed size during iteration" error? 我收到RuntimeError:字典在迭代过程中更改了大小。 蟒蛇 - I'm getting RuntimeError: dictionary changed size during iteration. Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM