在迭代Python时修改Python dict [英] Modifying a Python dict while iterating over it

查看:115
本文介绍了在迭代Python时修改Python dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个Python字典 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆