Resolve the problem of removing element newspaper exceptions when Python traverses the dictionary

  • 2020-05-12 02:47:00
  • OfStack

Wrong code


d = {'a':1, 'b':0, 'c':1, 'd':0}
for key, val in d.items():
  del(d[k])

Error code -- for Python3


d = {'a':1, 'b':0, 'c':1, 'd':0}
for key, val in d.keys():
  del(d[k])

Correct code


d = {'a':1, 'b':0, 'c':1, 'd':0}
keys = list(d.keys())
for key, val in keys:
  del(d[k])

Related articles: