To be safe, you must store the link somewhere. The use of idioms:
for k,v in list(d.items()):
Itโs not completely safe, because although it will work most of the time, during the last iteration of the loop, the list can be collected using garbage.
The right way:
items = list(d.items()) for k,v in items:
If you use WeakKeyDictionary , you can just save the keys and save the values โโif you use WeakValueDictionary .
On the side note: in python2 .items() list is already returned.
Ultimately, it depends on what you mean by โsafe.โ If you simply mean that the iteration will act correctly (repeated once on all elements), then:
for k,v in list(d.items()):
is safe because dictionary iteration is actually done by list(d.items()) , then you only iterate through the list.
If you instead mean that during the iteration the elements should not โdisappearโ from the dictionary as a side effect of for -loop, then you should keep the strong link until the end of the loop, and you need to save the list in a variable before starting the loop.
source share