Home  >  Article  >  Backend Development  >  Solve the problem of abnormal reporting when deleting elements when traversing the dictionary in Python

Solve the problem of abnormal reporting when deleting elements when traversing the dictionary in Python

高洛峰
高洛峰Original
2017-02-23 11:39:501540browse

Wrong code ①

##

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

Wrong 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])

The above article solves the problem of deleting elements and reporting exceptions when traversing Python dictionary. This is all the content shared by the editor. I hope it can give you a reference, and I also hope that everyone will support the PHP Chinese website.

For more related articles on solving the problem of abnormal reporting when deleting elements when traversing the dictionary in Python, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn