Perfect solution for Python traversal delete the null-value element in the dictionary error problem

Source: Internet
Author: User
The following small series to bring you a perfect solution to the Python traversal delete the value of the dictionary null element error problem. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

Exam = {' Math ': ' Up ', ' eng ': ' + ', ' CHN ': ' + ', ' phy ': ', ' Chem ': '}

Use the following traversal methods 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): File "untitled.py", line 3, in <module> for  E in Exam:RuntimeError:dictionar Y 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:

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 will traverse its keys, and in this process, you cannot change the dictionary! Cannot delete, add data

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

The above is a perfect solution to the Python traversal delete the value of the dictionary null element error problem is the small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we have a lot of support topic.alibabacloud.com.

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.