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

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

问题描述

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

(fg 只是一些黑盒转换.)

(f and g are just some black-box transformations.)

换句话说,我们尝试向 d 添加/删除项目,同时使用 iteritems 对其进行迭代.

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

推荐答案

在 Python 文档页面(对于 Python 2.7)

It is explicitly mentioned on the Python doc page (for Python 2.7) that

在字典中添加或删除条目时使用 iteritems() 可能会引发 RuntimeError 或无法遍历所有条目.

Using iteritems() while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries.

同样适用于 Python 3.

同样适用于 iter(d)d.iterkeys()d.itervalues(),我会去至于它对 for k, v in d.items() 的作用:(我不记得 for 究竟做了什么,但我不会感到惊讶如果实现调用 iter(d)).

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 dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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