Perfect solution Python Traversal delete the element with null value in the dictionary error problem _python

Source: Internet
Author: User

Exam = {' Math ': ' n ', ' eng ': ' n ', ' CHN ': ' N ', ' phy ': ', ' Chem ': '}

Use the following traversal method to delete:

1. For e in exam:
2. If exam[e] = = ':
3. Del Exam[e]

The result is the following error, How to resolve:

Traceback (most recent call last):
 File "untitled.py", line 3, in <module> to
  e in exam:
runtimeerror: Dictionary changed size during iteration

Correct procedure:

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:

4. #比如我要删除第四个元素

5.del s["4"]

Just in the For loop, which is equivalent to the operation of the linked list, it automatically calls the next method!

The dictionary iterator iterates through its keys, and in the process, you can't change the dictionary! Cannot delete, add data

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

The above perfect solution Python traversal Delete the value of the element is empty in the dictionary the error problem is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.