How to work, you need to update the dictionary

I need to remove a k / v pair from a dictionary in a loop. Having received RuntimeError: dictionary changed size during iteration, I picked up the dictionary after deleting k / v and in one of the external loops I try to open a new pickled / updated dictionary again. However, as many of you probably know - I get the same error - I think when it reaches the top of the loop. I do not use the dictionary in the outer loop.

So my question is: does anyone know how to get around this problem? I want to remove the k / V pair from the dictionary and use this modified dictionary in the next iteration of the loop.

to focus the problem and use the Cygil solution

list=[27,29,23,30,3,5,40]
testDict={}
for x in range(25):
    tempDict={}
    tempDict['xsquared']=x*x
    tempDict['xinverse']=1.0/(x+1.0)
    testDict[(x,x+1)]=tempDict

for item in list:
    print 'the Dictionary now has',len(testDict.keys()), ' keys'
    for key in testDict.keys():
        if key[0]==item:

        del testDict[key]

, , , - . , (, A), , ( B). . B, . 6000 , , , . , A, . B, .

+3
3

, - :

for key in dict:
    if check_condition(dict[key]):
       del dict[key]

,

for key in list(dict.keys()):
    if key in dict and check_condition(dict[key]):
        del dict[key]

list(dict.keys()) , , ( , ).

+6

, > 15:

for k in mydict.keys(): # makes a list of the keys and iterate
                        # over the list, not over the dict.
    if mydict[k] > 15:
        del mydict[k]
+4

Edit:

for ansSeries in notmatched:

To:

for ansSeries in notmatched.copy():
+1
source

Source: https://habr.com/ru/post/1705830/


All Articles