Home > Article > Backend Development > Solve the problem of abnormal reporting when deleting elements when traversing the dictionary in Python
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!