English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article describes a simple way to traverse a dictionary and delete elements in Python. Shared for everyone's reference, as follows:
This way is definitely problematic:
d = {'a':1, 'b':2, 'c':3} for key in d: d.pop(key)
Will report this error: RuntimeError: dictionary changed size during iteration
This way, Python2Is feasible, Python3And still report the above error.
d = {'a':1, 'b':2, 'c':3} for key in d.keys(): d.pop(key)
Python3The reason for the error is that the keys() function returns dict_keys instead of list. Python3A feasible way is as follows:
d = {'a':1, 'b':2, 'c':3} for key in list(d): d.pop(key)
Readers who are interested in more related content about Python can check the special topics of this site: 'Summary of Python Dictionary Operation Skills', 'Summary of Python File and Directory Operation Skills', 'Summary of Python Text File Operation Skills', 'Summary of Python URL Operation Skills', 'Summary of Python Image Operation Skills', 'Python Data Structures and Algorithms Tutorial', 'Summary of Python Socket Programming Skills', 'Summary of Python Function Usage Skills', 'Summary of Python String Operation Skills', and 'Classic Tutorial of Python Entry and Progression'.
I hope the content described in this article will be helpful to everyone in designing Python programs.
Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please replace '#' with '@' when sending an email for reporting violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.