Perfect solution to the error reporting problem of python traversal removing elements with empty values in the dictionary

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

exam = { 'math': '95', 'eng': '96', 'chn': '90', 'phy': '', 'chem': '' }

Delete using the following traversal method:

1. for e in exam:
2. if exam[e] == '':
3. del exam[e]

Results: the following errors occurred. How to solve them?


Traceback (most recent call last):
 File "Untitled.py", line 3, in <module>
  for e in exam:
RuntimeError: dictionary changed size during iteration

Correct practice:

1. s = {"1":a,"2":b,"3":c,"4":d,"5":e}
2. s_key = list(s.keys())
3. for k_s in s_key:

Let's say I want to delete the fourth element

5.del s["4"]

Only in the for loop, which is the equivalent of an operation on a linked list, it automatically calls the next method!

The iterator of the dictionary will iterate over its keys, and in the process, the dictionary cannot be changed! Cannot delete or add data

To record the index of the element to be deleted, and then delete it after traversing, exam.keys () returns a separate list


Related articles: