Python interview topic (for dict or set data type) Edge Traversal edge modification error dictionary changed size during iteration

Source: Internet
Author: User

    # result is a dictionary that removes      attribute values that are none  for inch Result:           if  not Result[key]:               del Result[key]               Continue  

But the error message is as follows

Runtimeerror:dictionary changed size during iteration   #

This error is thrown when Python iterates through a dict, set type, and changes the length of the variable or side-by-side modification.

After I looked up some information, I found that using the for in iteration is an iterator, or a linked list, that you cannot add or remove attributes at the time of the iteration, only the property values can be changed. (I do not understand the specific principle, then I will solve the problem first)

I think, there are two solutions, one is to convert the dictionary to a list, and then delete; Or if I don't traverse the dictionary and just walk through the dictionary's property names, I'm going to avoid this problem. I chose the back one, as needed, and I did.

This problem will appear in both Python2 and Python3;

Here are some ideas for python2 and Python3 on how to solve this kind of method:

Python2 traversal Dictvar.keys (), returns a list to get a list, which allows you to modify the dictionary  while iterating through the list, but this method is not available in Python3, as this is done by traversing Dictvar.keys (), returns an iterator instead of a list, so this time put the dictionary as a parameter in the list method so that a list can be returned;

See the workaround:

Python interview topic (for dict or set data type) Edge Traversal edge modification error dictionary changed size during iteration

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.