Whether Python should use keys () when iterating through a dictionary

Source: Internet
Author: User
Python2 words, should.

Because an iterative object can cause Runtime Error If it changes in length during the iteration, it for k in some_dict: is not possible to use or method in such a statement .pop() .update() :

RuntimeError                              Traceback (most recent)----> 1 for k in Foo:      2     foo.pop (k) Runtimeerror:dictionary C Hanged size during iteration

Unless you know for sure that the elements of the iteration object will not be removed from the operation, you should first take the keys out of the object and put them in another object ( keys() the list returned by the method) to avoid the above exception.

In Python3, however, the keys() list is not returned, but the properties of the object are iterated dict_keys , so this is not a feasible trick. Consider a list conversion, a pop after the end of the iteration, or use a dictionary derivation.

Whether Python should use keys () when iterating through a dictionary

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.