Python2 words, should.
Because an iterative object can cause Runtime Error If it changes in length during the iteration, it for k in some_dict:
is not possible to use or method in such a statement .pop()
.update()
:
RuntimeError Traceback (most recent)----> 1 for k in Foo: 2 foo.pop (k) Runtimeerror:dictionary C Hanged size during iteration
Unless you know for sure that the elements of the iteration object will not be removed from the operation, you should first take the keys out of the object and put them in another object ( keys()
the list returned by the method) to avoid the above exception.
In Python3, however, the keys()
list is not returned, but the properties of the object are iterated dict_keys
, so this is not a feasible trick. Consider a list conversion, a pop after the end of the iteration, or use a dictionary derivation.
Whether Python should use keys () when iterating through a dictionary