python遍历字典,for ele in dict 和 for ele in list(dict.keys())的区别

最近在工程中遇到了一个问题,在review代码的时候发现了遍历字典的这样一个写法:for ele in list(dict.keys())(这里用的是python3,如果是python2的话应该是for ele in dict.keys(),因为在python3中dict.keys()是一个迭代器),感觉可以精简成for ele in dict这种写法,但是修改之后报错:dictionary changed size during iteration。

查了资料后得到如下结论,一般不涉及到更改字典内容的情况下,由for ele in list(dict.keys())改为or ele in dict是没有问题的。但是如果在遍历过程中会对字典内容做修改,就必须使用for ele in list(dict.keys())这种方式。官方文档中给的解释是:The objects returned by dict.keys(), dict.values() and dict.items() are view objects. They provide a dynamic view on the dictionary’s entries, which means that when the dictionary changes, the view reflects these changes.

附官方文档链接:https://docs.python.org/3/library/stdtypes.html#dict-views

你可能感兴趣的:(python遍历字典,for ele in dict 和 for ele in list(dict.keys())的区别)