Home > Backend Development > Python Tutorial > 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

高洛峰
Release: 2017-02-23 11:39:50
Original
1561 people have browsed it

Wrong code ①

##

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

Wrong code ② -- For Python3

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

Correct code

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template