dictionary - Modifying a Python dict while iterating over it -


let's have python dictionary d, , we're iterating on so:

for k,v in d.iteritems():     del d[f(k)] # remove item     d[g(k)] = v # add new item 

(f , g black-box transformations.)

in other words, try add/remove items d while iterating on using iteritems.

is defined? provide references support answer?

(it's pretty obvious how fix if it's broken, isn't angle after.)

it explicitly mentioned on python doc page (for python 2.7) that

using iteritems() while adding or deleting entries in dictionary may raise runtimeerror or fail iterate on entries.

similarly python 3.

the same holds iter(d), d.iterkeys() , d.itervalues(), , i'll go far saying for k, v in d.items(): (i can't remember for does, not surprised if implementation called iter(d)).


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -