RuntimeError: OrderedDict mutated during iteration 在python里的解决办法

之前的代码是

for i in products:
            product=products[i]
            filename=product['filename']
            print(filename) 
            #print filename[26:30]
            if filename[26:30] == imagename[26:30]:
                downfiles[i]=product
                print('YES,it works!')        
                #api.download(i, directory_path=path)
            else:
                print('NO!')
                products.pop(i)

结果报错是RuntimeError: OrderedDict mutated during iteration,说在for i in products:中出现问题

看了http://www.pianshen.com/article/1281305758/

之后修改为以下代码,成功了

 

for i in list(products.keys()):
            product=products[i]
            filename=product['filename']
            print(filename) 
            #print filename[26:30]
            if filename[26:30] == imagename[26:30]:
                downfiles[i]=product
                print('YES,it works!')        
                #api.download(i, directory_path=path)
            else:
                print('NO!')
                products.pop(i)

 

你可能感兴趣的:(python)