最近在工程中遇到了一個問題忠售,在review代碼的時候發(fā)現(xiàn)了遍歷字典的這樣一個寫法: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