遍历my_dict.keys()并修改字典中的值是否会使迭代器无效? [英] Does iterating over my_dict.keys() and modifying the values in the dictionary invalidate the iterator?

查看:171
本文介绍了遍历my_dict.keys()并修改字典中的值是否会使迭代器无效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的例子是这样的

for my_key in my_dict.keys():
    my_dict[my_key].mutate()

上述代码的行为是否已定义(假设my_dict是字典,而mutate是对其对象进行变异的方法)?我担心的是,修改字典中的值可能会使迭代器在字典键上的作用无效.

Is the behavior of the above code defined (assuming my_dict is a dictionary and mutate is a method that mutates its object)? My concern is that mutating the values in the dictionary might invalidate the iterator over the keys of the dictionary.

另一方面,keys方法的 Python文档指示它返回一个列表.如果是这样,只要(我认为)我不改变,添加或删除任何键,就应该能够改变字典的值,并且仍然可以安全地访问字典的每个元素.正确吗?

On the other hand, the Python documentation of the keys method indicates that it returns a list. If so, I should (I think) be able to mutate the dictionary's values and still access every element of the dictionary safely as long as I don't mutate, add, or remove any of the keys. Is that correct?

推荐答案

是的,至少在所有基于C的Python实现中都是安全的.这样做也是安全的:

Yes, that's safe, at least in all of the C-based implementations of Python. It's also safe to do:

for my_key in my_dict: # NOTE:  no .keys() here
    my_dict[my_key].mutate()

也就是说,安全性并不取决于具体化按键列表,通常,不仅仅为了遍历按键而调用.keys()更为有效.

That is, the safety does not depend on materializing a list of the keys, and it's generally more efficient not to call .keys() just to iterate over the keys.

请注意,在迭代过程中完全替换与现有键相关联的值也可以:

Note that it's also fine to entirely replace values associated with existing keys during iteration:

for my_key in my_dict:
    my_dict[my_key] = something_new()

有关此文档的文档可能会更清楚;-)可预测的安全的是在迭代过程中删除或添加密钥.您对值做的事没关系.

The docs could be clearer about this ;-) What isn't predictably safe is removing or adding keys during iteration. What you do to the values doesn't matter.

这篇关于遍历my_dict.keys()并修改字典中的值是否会使迭代器无效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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