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

今天药忘吃喽~ 2022-04-24 20:16 200阅读 0赞

之前的代码是

  1. for i in products:
  2. product=products[i]
  3. filename=product['filename']
  4. print(filename)
  5. #print filename[26:30]
  6. if filename[26:30] == imagename[26:30]:
  7. downfiles[i]=product
  8. print('YES,it works!')
  9. #api.download(i, directory_path=path)
  10. else:
  11. print('NO!')
  12. products.pop(i)

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

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

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

  1. for i in list(products.keys()):
  2. product=products[i]
  3. filename=product['filename']
  4. print(filename)
  5. #print filename[26:30]
  6. if filename[26:30] == imagename[26:30]:
  7. downfiles[i]=product
  8. print('YES,it works!')
  9. #api.download(i, directory_path=path)
  10. else:
  11. print('NO!')
  12. products.pop(i)

发表评论

表情:
评论列表 (有 0 条评论,200人围观)

还没有评论,来说两句吧...

相关阅读