python RuntimeError: dictionary changed size during iteration

前端 未结 5 1958
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 12:32

I have obj like this

{hello: \'world\', \"foo.0.bar\": v1, \"foo.0.name\": v2, \"foo.1.bar\": v3}

It should be expand to

{         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 13:00

    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! 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.

    The solution is to convert your defaultdict to dict before looping through it, i.e.

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

    or make sure you're not adding/removing any keys while iterating through it.

提交回复
热议问题