在迭代Python时修改Python dict [英] Modifying a Python dict while iterating over it
问题描述
d
,我们正在这样迭代: for k,v in d.iteritems():
del d [f(k)]#删除一些项目
d [g(k)] = v#add一个新项目
( f
和 g
只是一些黑盒子转换。)
换句话说,我们尝试添加/删除项目到code> d 同时使用 iteritems
进行迭代。
界定?你可以提供一些参考来支持你的答案吗?
(很明显,如果它是坏的,如何解决这个问题,所以这不是我之后的角度。 / p>
在Python文档页面中明确提到: http://docs.python.org/library/stdtypes.html#dict.iteritems 使用iteritems()while添加或删除字典中的条目可能引起RuntimeError或无法遍历所有条目
。
同样适用于 iter(d)
, d.iterkeys()
和 d.itervalues()
,我会去说,对于k,v在d.items()中的:
(我不记得什么 for
,但是如果实现称为 iter(d)
),则不会感到惊讶。
Let's say we have a Python dictionary d
, and we're iterating over it like so:
for k,v in d.iteritems():
del d[f(k)] # remove some item
d[g(k)] = v # add a new item
(f
and g
are just some black-box transformations.)
In other words, we try to add/remove items to d
while iterating over it using iteritems
.
Is this well defined? Could you provide some references to support your answer?
(It's pretty obvious how to fix this if it's broken, so this isn't the angle I am after.)
It is explicitely mentioned on the Python doc page: http://docs.python.org/library/stdtypes.html#dict.iteritems that Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries
.
The same holds for iter(d)
, d.iterkeys()
and d.itervalues()
, and I'll go as far as saying that it does for for k, v in d.items():
(I can't remember exactly what for
does, but I would not be surprised if the implementation called iter(d)
).
这篇关于在迭代Python时修改Python dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!