Python simply traverses the dictionary and removes elements

  • 2020-05-12 02:48:52
  • OfStack

This example shows how Python can simply traverse a dictionary and delete elements. I will share it with you for your reference as follows:

There must be something wrong with this approach:


d = {'a':1, 'b':2, 'c':3}
for key in d:
  d.pop(key)

This error will be reported: RuntimeError: dictionary changed size during iteration

Python2 works this way, but Python3 still reports the above error.


d = {'a':1, 'b':2, 'c':3}
for key in d.keys():
  d.pop(key)

The reason Python3 is reporting an error is that the keys() function returns dict_keys instead of list. Possible ways of Python3 are as follows:


d = {'a':1, 'b':2, 'c':3}
for key in list(d):
  d.pop(key)

For more information about Python, please visit our site: Python dictionary skills summary, Python file and directory skills summary ", "Python skills summary text file", "Python URL skills summary", "Python pictures skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using skills summary", "Python string skills summary" and "Python introductory and advanced tutorial"

I hope this article is helpful to you Python programming.


Related articles: